【AWS】AWS CLIを利用してPostfixのメールキューを監視する。

# 1. はじめに
### 1-1 ご挨拶
初めまして、井村と申します。
AWSのAmazon Linux 2023にPostfixをインストールしメールキューの監視設定を行いました。
メールキューの数をCloudWatchに転送します。
備忘録の記事になります。

### 1-2 対象読者
- AWSに興味がある
- 監視に興味がある

### 1-3 メールキューの監視方法について
サーバ上でaws cliコマンドを利用します。引数としてメールキューの総数を取得、CloudWatchへ転送します。定期的にメトリクスを送りますのでクーロンも同時に設定します。

# 2. 構築
### 2-1 test.yaml構成

CloudFormationで各リソースを作成します。

<details><summary>test.yaml</summary>

```yaml:test.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Simple Web Architecture

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
    - Label:
        default: "Common"
      Parameters:
        - SystemName
        - EnvType
    - Label:
        default: "EC2 Configuration"
      Parameters:
        - LastestAmiId

Parameters:
  SystemName:
      Description: "Enter System name"
      Type: String
      Default: "timura"
  EnvType:
      Description: "Select Environment type"
      Type: String
      Default: "dev"
      AllowedValues:
      - "dev"
      - "prod"
  LatestAmiId:
      Type: AWS::SSM::Parameter::Value<String>
      Default: "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"


Mappings:
  EnvConfig:
    prod:
      EC2InstanceType: t3.micro
      EC2DiskSize: 20
      RDSInstanceType: db.t3.micro
      RDSStorageSize: 20
    dev:
      EC2InstanceType: t2.micro
      EC2DiskSize: 20
      RDSInstanceType: db.t3.micro
      RDSStorageSize: 20

Resources:
  VPC:
      Type: AWS::EC2::VPC
      Properties:
        CidrBlock: 10.0.0.0/16
        EnableDnsSupport: true
        EnableDnsHostnames: true
        InstanceTenancy: default
        Tags:
          - Key: Name
            Value: !Sub ${SystemName}-${EnvType}-vpc

  PublicSubnet01:
      Type: AWS::EC2::Subnet
      Properties:
          VpcId: !Ref VPC
          CidrBlock: 10.0.1.0/24
          AvailabilityZone: !Select [ 0, !GetAZs "" ]
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-public-subnet01

  PublicSubnet02:
      Type: AWS::EC2::Subnet
      Properties:
          VpcId: !Ref VPC
          CidrBlock: 10.0.2.0/24
          AvailabilityZone: !Select [ 1, !GetAZs "" ]
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-public-subnet02

  PrivateSubnet01:
      Type: AWS::EC2::Subnet
      Properties:
          VpcId: !Ref VPC
          CidrBlock: 10.0.3.0/24
          AvailabilityZone: !Select [ 0, !GetAZs "" ]
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-private-subnet01

  PrivateSubnet02:
      Type: AWS::EC2::Subnet
      Properties:
          VpcId: !Ref VPC
          CidrBlock: 10.0.4.0/24
          AvailabilityZone: !Select [ 1, !GetAZs "" ]
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-private-subnet02

  InternetGateway:
      Type: AWS::EC2::InternetGateway
      Properties:
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-igw

  AttachGateway:
      Type: AWS::EC2::VPCGatewayAttachment
      Properties:
          VpcId: !Ref VPC
          InternetGatewayId: !Ref InternetGateway

  NatGatewayEIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc

  NatGateway:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGatewayEIP.AllocationId
      SubnetId: !Ref PublicSubnet01
      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-ngw

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-public-rtb

  PrivateRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-private-rtb

  PublicRoute:
    Type: AWS::EC2::Route
    DependsOn: AttachGateway
    Properties:
          RouteTableId: !Ref PublicRouteTable
          DestinationCidrBlock: '0.0.0.0/0'
          GatewayId: !Ref InternetGateway

  PrivateRoute:
    Type: AWS::EC2::Route
    Properties:
          RouteTableId: !Ref PrivateRouteTable
          DestinationCidrBlock: '0.0.0.0/0'
          NatGatewayId: !Ref NatGateway

  PublicSubnet01RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet01

  PublicSubnet02RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet02

  PrivateSubnet01RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTable
      SubnetId: !Ref PrivateSubnet01

  PrivateSubnet02RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTable
      SubnetId: !Ref PrivateSubnet02

  ALBSecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          GroupName: !Sub ${SystemName}-${EnvType}-alb-sg
          GroupDescription: "Allow http https from users"
          VpcId: !Ref VPC
          SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: "0.0.0.0/0"
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-alb-sg

  EC2SecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
          GroupName: !Sub ${SystemName}-${EnvType}-ec2-sg
          GroupDescription: "Allow http https from alb"
          VpcId: !Ref VPC
          SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            SourceSecurityGroupId: !Ref ALBSecurityGroup
          Tags:
              - Key: Name
                Value: !Sub ${SystemName}-${EnvType}-ec2-sg

  EC2Role:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub ${SystemName}-${EnvType}-ec2-role
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
        - arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy

  EC2Profile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: !Sub ${SystemName}-${EnvType}-ec2-profile
      Roles:
        - !Ref EC2Role

  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: !FindInMap [ EnvConfig, !Ref EnvType, EC2InstanceType ]
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeType: gp3
            VolumeSize: !FindInMap [ EnvConfig, !Ref EnvType, EC2DiskSize ]
      SecurityGroupIds:
        - !Ref EC2SecurityGroup
      SubnetId: !Ref PrivateSubnet01
      IamInstanceProfile: !Ref EC2Profile
      UserData:
        "Fn::Base64": |
          #!/bin/bash
          dnf update -y
          dnf install -y postfix
          dnf install -y mailx # mailコマンド
          dnf install -y cronie # crontabのため
          systemctl enable postfix
          systemctl stop postfix
          systemctl enable crond
          systemctl start crond

      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-ec2

  ALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: !Sub ${SystemName}-${EnvType}-alb
      Scheme: internet-facing
      Type: application
      Subnets:
        - !Ref PublicSubnet01
        - !Ref PublicSubnet02
      SecurityGroups:
        - !Ref ALBSecurityGroup
      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-alb

  ALBTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Sub ${SystemName}-${EnvType}-alb-tg
      VpcId: !Ref VPC
      TargetType: instance
      Port: 80
      Protocol: HTTP
      Targets:
        - Id: !Ref EC2Instance
          Port: 80
      HealthCheckProtocol: HTTP
      Tags:
        - Key: Name
          Value: !Sub ${SystemName}-${EnvType}-alb-tg

  ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref ALBTargetGroup
      LoadBalancerArn: !Ref ALB
      Port: 80
      Protocol: HTTP
```
</details>


セッションマネージャーからEC2にログイン後、以下コマンドを実行していきます。
実行結果も載せています。

### 2-2 クーロンの設定

まずはコンフィグ設定を実施します。権限はCloudFormationにて設定済みですので、リージョンとアウトプットフォーマットの設定のみになります。

```
aws configure
```

```
[ec2-user@ip-10-0-3-117 ~]$ aws configure
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]: ap-northeast-1
Default output format [None]: json
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ cat .aws/config
[default]
region = ap-northeast-1
output = json
[ec2-user@ip-10-0-3-117 ~]$
```

次は定期的にメトリクスを取得するシェルを作成します。今回選定したディレクトリはローカルサーバから投稿されたメールキューを溜めるmaildropになります。

以下がシェルになります。インスタンスIdはコンソール画面からEC2のインスタンスIDを取得し、置き換えます。

```
sudo cat > maildrop.sh << 'EOF'
#!/bin/bash

metric_name="maildrop"
name_space="AWS/EC2"
InstanceId="インスタンスId"

# maildropに溜まるメールキュー数を取得
maildrop=`sudo ls -l /var/spool/postfix/maildrop | wc -l`

/usr/bin/aws cloudwatch --region "ap-northeast-1" put-metric-data --metric-name "${metric_name}" --namespace ${name_space} --value ${maildrop} --dimensions InstanceId=${InstanceId}
EOF
```

```
[ec2-user@ip-10-0-3-117 ~]$ sudo mkdir /opt/shell/
[ec2-user@ip-10-0-3-117 ~]$ sudo chown ec2-user:ec2-user /opt/shell/
[ec2-user@ip-10-0-3-117 ~]$ cd /opt/shell/
[ec2-user@ip-10-0-3-117 shell]$
[ec2-user@ip-10-0-3-117 shell]$ cat > maildrop.sh << 'EOF'
#!/bin/bash

metric_name="maildrop"
name_space="AWS/EC2"
InstanceId="i-032bd3e5340acbead"

# maildropに溜まるメールキュー数を取得
maildrop=`sudo ls -l /var/spool/postfix/maildrop | wc -l`

/usr/bin/aws cloudwatch --region "ap-northeast-1" put-metric-data --metric-name "${metric_name}" --namespace ${name_space} --value ${maildrop} --dimensions InstanceId=${InstanceId}
EOF
[ec2-user@ip-10-0-3-117 shell]$ chmod +x maildrop.sh ; ls -l maildrop.sh
-rwxr-xr-x. 1 ec2-user ec2-user 384 May 24 10:37 maildrop.sh
[ec2-user@ip-10-0-3-117 shell]$
```

それではクーロンの設定、実行を行います。5分間隔でメトリクスを送ります。

```
crontab -e

sudo systemctl restart crond
```

```
[ec2-user@ip-10-0-3-117 shell]$ crontab -e
no crontab for ec2-user - using an empty one
crontab: installing new crontab
[ec2-user@ip-10-0-3-117 shell]$
[ec2-user@ip-10-0-3-117 shell]$ crontab -l
*/5 * * * * /opt/shell/maildrop.sh
[ec2-user@ip-10-0-3-117 shell]$
[ec2-user@ip-10-0-3-117 shell]$ sudo systemctl restart crond
[ec2-user@ip-10-0-3-117 shell]$
[ec2-user@ip-10-0-3-117 shell]$ sudo systemctl status crond
● crond.service - Command Scheduler
     Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; preset: enabled)
     Active: active (running) since Sat 2025-05-24 10:41:11 UTC; 7s ago
   Main PID: 28642 (crond)
      Tasks: 2 (limit: 1111)
     Memory: 1.3M
        CPU: 3ms
     CGroup: /system.slice/crond.service
             ├─27142 /usr/sbin/anacron -s
             └─28642 /usr/sbin/crond -n

May 24 10:41:11 ip-10-0-3-117.ap-northeast-1.compute.internal systemd[1]: Started crond.service - Command Scheduler.
May 24 10:41:11 ip-10-0-3-117.ap-northeast-1.compute.internal crond[28642]: (CRON) STARTUP (1.5.7)
May 24 10:41:11 ip-10-0-3-117.ap-northeast-1.compute.internal crond[28642]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 99% if used.)
May 24 10:41:11 ip-10-0-3-117.ap-northeast-1.compute.internal crond[28642]: (CRON) INFO (running with inotify support)
May 24 10:41:11 ip-10-0-3-117.ap-northeast-1.compute.internal crond[28642]: (CRON) INFO (@reboot jobs will be run at computer's startup.)
[ec2-user@ip-10-0-3-117 shell]$
```

これで構築は終了です。


# 3. 確認

CloudWatchにてメトリクスを確認します。

コンソール画面からすべてのメトリクスをえらびEC2のインスタンスIDを入力します。
メトリクスからシェルで設定したmaildropが確認できます。
※1がカウントされているのはwc-lの出力結果がカウントされて常に1となります。。

![cloudwatch3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1989465/76184c47-3c27-4543-8dd1-770197391e04.png)


# 4. 検証

ここから検証を行います。
postfixを停止し、ローカルサーバからメールを発行します。postfixが停止しているので、受信ボックスに格納されずメールキューがたまることを確認します。

まずは受信ボックスとメールキューが溜まるディレクトリを確認します。

```
# 受信ボックスの確認
[ec2-user@ip-10-0-3-117 ~]$ mail
No mail for ec2-user
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/mail/
total 0
-rw-rw----. 1 ec2-user mail 0 May 24 09:50 ec2-user
-rw-rw----. 1 rpc      mail 0 May  9 22:23 rpc
-rw-rw----. 1 ssm-user mail 0 May 24 10:12 ssm-user
[ec2-user@ip-10-0-3-117 ~]$
```

```
# メールキューディレクトリの確認
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/postfix/
total 0
drwx------. 2 postfix root     6 Jan 16  2024 active
drwx------. 2 postfix root     6 Jan 16  2024 bounce
drwx------. 2 postfix root     6 Jan 16  2024 corrupt
drwx------. 2 postfix root     6 Jan 16  2024 defer
drwx------. 2 postfix root     6 Jan 16  2024 deferred
drwx------. 2 postfix root     6 Jan 16  2024 flush
drwx------. 2 postfix root     6 Jan 16  2024 hold
drwx------. 2 postfix root     6 Jan 16  2024 incoming
drwx-wx---. 2 postfix postdrop 6 Jan 16  2024 maildrop
drwxr-xr-x. 2 root    root     6 Jan 16  2024 pid
drwx------. 2 postfix root     6 Jan 16  2024 private
drwx--x---. 2 postfix postdrop 6 Jan 16  2024 public
drwx------. 2 postfix root     6 Jan 16  2024 saved
drwx------. 2 postfix root     6 Jan 16  2024 trace
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/postfix/maildrop/
total 0
[ec2-user@ip-10-0-3-117 ~]$
```

Postfixが停止さていることを確認します。

```
[ec2-user@ip-10-0-3-117 ~]$ sudo systemctl status postfix
○ postfix.service - Postfix Mail Transport Agent
     Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; preset: disabled)
     Active: inactive (dead)
[ec2-user@ip-10-0-3-117 ~]$
```

景気よくメールを100通投稿しましょう！

```
[ec2-user@ip-10-0-3-117 ~]$ touch send_test_mail.sh; chmod a+x send_test_mail.sh
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ cat > send_test_mail.sh << EOF
> #!/bin/bash

for i in {1..100}
do
  echo "This is a test mail from postfix" | mail -s "Test Mail!!" ec2-user@localhost &
done
> EOF
[ec2-user@ip-10-0-3-117 ~]$

# シェル実行
[ec2-user@ip-10-0-3-117 ~]$ ./send_test_mail.sh &
[1] 37344
[ec2-user@ip-10-0-3-117 ~]$
[1]+  Done                    ./send_test_mail.sh
[ec2-user@ip-10-0-3-117 ~]$
```

メールキューおよび受信ボックスを確認します。
以下よりメールキューが100件、受信ボックスが0であることがわかります。

```
[ec2-user@ip-10-0-3-117 ~]$ ls -l /var/spool/postfix/
total 32
drwx------. 2 postfix root         6 May 24 13:11 active
drwx------. 2 postfix root         6 May 24 13:11 bounce
drwx------. 2 postfix root         6 Jan 16  2024 corrupt
drwx------. 2 postfix root         6 Jan 16  2024 defer
drwx------. 2 postfix root         6 Jan 16  2024 deferred
drwx------. 2 postfix root         6 Jan 16  2024 flush
drwx------. 2 postfix root         6 Jan 16  2024 hold
drwx------. 2 postfix root         6 May 24 13:11 incoming
drwx-wx---. 2 postfix postdrop 16384 May 24 13:42 maildrop
drwxr-xr-x. 2 root    root        63 May 24 13:15 pid
drwx------. 2 postfix root     16384 May 24 13:11 private # ここは検証ミスでゴミです。
drwx--x---. 2 postfix postdrop    88 May 24 13:11 public
drwx------. 2 postfix root         6 Jan 16  2024 saved
drwx------. 2 postfix root         6 Jan 16  2024 trace
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/postfix/maildrop/
total 400
-rwxr--r--. 1 ec2-user postdrop 351 May 24 13:42 01E151007E55
-rwxr--r--. 1 ec2-user postdrop 352 May 24 13:42 048E81007E56
-rwxr--r--. 1 ec2-user postdrop 352 May 24 13:42 0499E1007E57
～省略～
-rwxr--r--. 1 ec2-user postdrop 353 May 24 13:42 EC8281007E51
-rwxr--r--. 1 ec2-user postdrop 353 May 24 13:42 EE5D31007E53
-rwxr--r--. 1 ec2-user postdrop 353 May 24 13:42 F19FC1007E54
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/postfix/maildrop/ | wc -l
101
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ mail
No mail for ec2-user
[ec2-user@ip-10-0-3-117 ~]$
```

それではPostfixを起動させメールを受信ボックスに送ります。
```
[ec2-user@ip-10-0-3-117 ~]$ sudo systemctl start postfix
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ systemctl status postfix
● postfix.service - Postfix Mail Transport Agent
     Loaded: loaded (/usr/lib/systemd/system/postfix.service; enabled; preset: disabled)
     Active: active (running) since Sat 2025-05-24 13:50:03 UTC; 32s ago
    Process: 38199 ExecStartPre=/usr/sbin/restorecon -R /var/spool/postfix/pid/master.pid (code=exited, status=255/EXCEPTION)
    Process: 38200 ExecStartPre=/usr/libexec/postfix/aliasesdb (code=exited, status=0/SUCCESS)
    Process: 38202 ExecStartPre=/usr/libexec/postfix/chroot-update (code=exited, status=0/SUCCESS)
    Process: 38203 ExecStart=/usr/sbin/postfix start (code=exited, status=0/SUCCESS)
   Main PID: 38270 (master)
      Tasks: 9 (limit: 1111)
     Memory: 6.1M
        CPU: 422ms
     CGroup: /system.slice/postfix.service
             ├─38270 /usr/libexec/postfix/master -w
             ├─38271 pickup -l -t unix -u
             ├─38272 qmgr -l -t unix -u
             ├─38273 cleanup -z -t unix -u
             ├─38274 trivial-rewrite -n rewrite -t unix -u
             ├─38275 local -t unix
             ├─38276 local -t unix
             ├─38277 local -t unix
             └─38278 cleanup -z -t unix -u

May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/cleanup[38278]: E67E9827E0F: message-id=<20250524135003.E67E9827E0F@ip-10-0-3-117.ap-northeast-1.compute.internal>
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/qmgr[38272]: E67E9827E0F: from=<ec2-user@ip-10-0-3-117.ap-northeast-1.compute.internal>, size=570, nrcpt=1 (queue active)
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/local[38275]: E4D4E827E0D: to=<ec2-user@localhost>, relay=local, delay=427, delays=427/0.01/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/qmgr[38272]: E4D4E827E0D: removed
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/local[38277]: E59A1827E0E: to=<ec2-user@localhost>, relay=local, delay=427, delays=427/0.01/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/qmgr[38272]: E59A1827E0E: removed
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/local[38275]: E67E9827E0F: to=<ec2-user@localhost>, relay=local, delay=427, delays=427/0/0/0, dsn=2.0.0, status=sent (delivered to mailbox)
May 24 13:50:03 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/qmgr[38272]: E67E9827E0F: removed
May 24 13:50:04 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/local[38276]: 9D0BD827E0A: to=<ec2-user@localhost>, relay=local, delay=429, delays=427/0.01/0/1.2, dsn=2.0.0, status=sent (delivered to mailbox)
May 24 13:50:04 ip-10-0-3-117.ap-northeast-1.compute.internal postfix/qmgr[38272]: 9D0BD827E0A: removed
You have mail in /var/spool/mail/ec2-user
[ec2-user@ip-10-0-3-117 ~]$
[ec2-user@ip-10-0-3-117 ~]$ sudo ls -l /var/spool/postfix/maildrop/
total 0
[ec2-user@ip-10-0-3-117 ~]$
```

```
[ec2-user@ip-10-0-3-117 ~]$ mail
Heirloom Mail version 12.5 7/5/10.  Type ? for help.
"/var/spool/mail/ec2-user": 100 messages 100 new
>N  1 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  2 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  3 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  4 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  5 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  6 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  7 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  8 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N  9 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 10 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 11 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 12 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 13 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 14 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 15 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 16 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 17 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 18 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 19 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 20 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 21 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 22 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 23 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 24 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 25 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 26 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 27 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 28 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 29 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 30 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 31 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 32 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 33 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 34 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 35 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 36 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 37 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 38 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 39 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 40 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 41 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 42 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 43 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 44 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 45 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 46 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 47 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 48 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 49 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 50 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
 N 51 EC2 Default User      Sat May 24 13:50  18/781   "Test Mail!!"
& 1
Message  1:
From ec2-user@ip-10-0-3-117.ap-northeast-1.compute.internal  Sat May 24 13:50:03 2025
Return-Path: <ec2-user@ip-10-0-3-117.ap-northeast-1.compute.internal>
X-Original-To: ec2-user@localhost
Delivered-To: ec2-user@localhost
Date: Sat, 24 May 2025 13:42:55 +0000
To: ec2-user@localhost
Subject: Test Mail!!
User-Agent: Heirloom mailx 12.5 7/5/10
Content-Type: text/plain; charset=us-ascii
From: EC2 Default User <ec2-user@ip-10-0-3-117.ap-northeast-1.compute.internal>
Status: R

This is a test mail from postfix

& q
Held 100 messages in /var/spool/mail/ec2-user
[ec2-user@ip-10-0-3-117 ~]$
```

無事に受信ボックスにメールが届きました。
CloudWatchにも反映されています。

![cloudwatch4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1989465/136c6880-aa0b-4ca6-a6c3-10a18f6551b8.png)

実際の監視については参考記事より
incoming ->	activeを経由し受信ボックスや別のMTAにキューを転送します。
ですが、色々な残念な結果によりキューがdeferredやbounceに溜まるそうです。
そのためメトリクスではactive、deferredとbounceを取得し、deferredとbounceに閾値を設定し超過するとアラートする運用がいいのかなと思います。

# 5. 終わりに
本記事を最後まで読んで頂きましてありがとうございます。
aws cliを扱った案件に初めて参画したのでとても勉強になりました。

# 6. 参考記事
- [AWS：CloudWatchでロードアベレージを監視](https://www.wetch.co.jp/note/aws%ef%bc%9acloudwatch%e3%81%a7%e3%83%ad%e3%83%bc%e3%83%89%e3%82%a2%e3%83%99%e3%83%ac%e3%83%bc%e3%82%b8%e3%82%92%e7%9b%a3%e8%a6%96/)
- [Postfix の概要 - キューマネージメント](https://postfix-jp.info/trans-2.0/jhtml/queuing.html)
- [キューの管理](http://unixservermemo.web.fc2.com/sv/postfix-queue.htm)
- [Postfix アーキテクチャの概要](https://www.postfix-jp.info/trans-2.1/jhtml/OVERVIEW.html)
- [How to configure Postfix mail queue monitoring in zabbix?](https://www.linuxquestions.org/questions/linux-server-73/how-to-configure-postfix-mail-queue-monitoring-in-zabbix-4175617865/)