RHELのメトリクス・ログをCloudWatchに自動アップロード

こんにちは
株式会社クラスアクト インフラストラクチャ事業部の大塚です。

一年ほど前に、勉強の為にWindowsのイベントログをCloudWatch Logsにアップロードする手順を確認しました。
今回はRHELで同様の事をする環境を作ってみたいと思います。

https://qiita.com/ohtsuka-shota/items/5dcf7118affc9c97f74f

# 環境イメージ
![growi-ページ34.drawio.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/95afaf17-cd32-4e85-8c32-35fc93cfc980.png)

# 構築手順
まず、RHELのEC2に対してアタッチするIAMロールを作成してきたいと思います。
![screencapture-us-east-1-console-aws-amazon-iam-home-2025-05-04-21_08_05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/58d675f4-9aaa-4ef4-8242-b6d5ee1d5987.png)

本来であれば権限は絞るべきですが、今回はCloudWatchFullAccessV2を選択して次へ
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/b28d28af-de7a-4dc1-85f7-95671dee855b.png)

名前をkensyo-cloudwatchlogsとしてロールを作成を押下します。
![screencapture-us-east-1-console-aws-amazon-iam-home-2025-05-04-21_10_57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/6d507f45-a7af-411a-9ba8-4df6b38777fc.png)

IAMロールが作成できたことを確認します。
![image (1).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/8f8d9368-b9d6-4e35-b6ea-7262e73608d7.png)

RHELのEC2を雑に作っていきます。
![screencapture-ap-northeast-1-console-aws-amazon-ec2-home-2025-05-04-21_06_27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/6067c74b-9d02-436e-93da-99cedecde3d9.png)

作成したEC2に先ほど用意したIAMロールをアタッチします。
![image (2).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/2054b3e3-965c-4a2c-b983-05f0e12a9230.png)

EC2インスタンスにSSHで接続し、CloudWatch AgentのRPMパッケージをダウンロードして、直接インストールを行っています。

https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/monitoring/download-cloudwatch-agent-commandline.html

```
[ec2-user@ip-192-168-100-7 ~]$ sudo su -
[root@ip-192-168-100-7 ~]# yum update
[root@ip-192-168-100-7 ~]# yum -y install wget
[root@ip-192-168-100-7 ~]# uname -m
x86_64
[root@ip-192-168-100-7 ~]# wget https://amazoncloudwatch-agent.s3.amazonaws.com/redhat/amd64/latest/amazon-cloudwatch-agent.rpm
[root@ip-192-168-100-7 ~]# ls
amazon-cloudwatch-agent.rpm
[root@ip-192-168-100-7 ~]# rpm -U ./amazon-cloudwatch-agent.rpm
```

設定ファイル（config.json）を新規で作成し、/opt/aws/amazon-cloudwatch-agent/etc/に配置します。
```
[root@ip-192-168-100-7 ~]# cd /opt/aws/amazon-cloudwatch-agent/etc
[root@ip-192-168-100-7 etc]# ls
amazon-cloudwatch-agent.d  common-config.toml
[root@ip-192-168-100-7 etc]# vi config.json
[root@ip-192-168-100-7 etc]# cat config.json
{
    "agent": {
        "metrics_collection_interval": 60,
        "run_as_user": "cwagent"
    },
    "metrics": {
        "append_dimensions": {
            "InstanceId": "${aws:InstanceId}"
        },
        "metrics_collected": {
            "cpu": {
                "measurement": [
                    "usage_idle",
                    "usage_iowait",
                    "usage_user",
                    "usage_system"
                ],
                "metrics_collection_interval": 60,
                "resources": [
                    "*"
                ]
            },
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 60
            }
        }
    },
    "logs": {
        "logs_collected": {
            "files": {
                "collect_list": [
                    {
                        "file_path": "/var/log/messages",
                        "log_group_name": "rhel-test-varlogmessages",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/secure",
                        "log_group_name": "rhel-test-varlogsecure",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/cron",
                        "log_group_name": "rhel-test-varlogcron",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/audit/audit.log",
                        "log_group_name": "rhel-test-varaudit",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/dnf.log",
                        "log_group_name": "rhel-test-vardnf",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/maillog",
                        "log_group_name": "rhel-test-varmaillog",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/cloud-init-output.log",
                        "log_group_name": "rhel-test-varcloud-init",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    },
                    {
                        "file_path": "/var/log/wtmp",
                        "log_group_name": "rhel-test-varwtmp",
                        "log_stream_name": "{instance_id}",
                        "timezone": "UTC"
                    }
                ]
            }
        },
        "log_stream_name": "rhel-test-cloudwatch-logs",
        "force_flush_interval": 5
    }
}
```

CloudWatch Agentの起動
-a fetch-configは設定を取得し、-sはエージェントを起動するオプション。
※config.jsonを書き換えた時は、そのconfigを反映させるためにもこのコマンドを使うっぽい。
```
[root@ip-192-168-100-7 etc]# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/config.json
****** processing amazon-cloudwatch-agent ******
I! Trying to detect region from ec2 D! [EC2] Found active network interface I! imds retry client will retry 1 timesSuccessfully fetched the config and saved in /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/file_config.json.tmp
Start configuration validation...
2025/05/10 01:37:57 Reading json config file path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/file_config.json.tmp ...
2025/05/10 01:37:57 I! Valid Json input schema.
2025/05/10 01:37:57 D! ec2tagger processor required because append_dimensions is set
2025/05/10 01:37:57 Configuration validation first phase succeeded
I! Detecting run_as_user...
I! Trying to detect region from ec2
D! [EC2] Found active network interface
I! imds retry client will retry 1 times
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -schematest -config /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml
Configuration validation second phase succeeded
Configuration validation succeeded
amazon-cloudwatch-agent has already been stopped
Created symlink /etc/systemd/system/multi-user.target.wants/amazon-cloudwatch-agent.service → /etc/systemd/system/amazon-cloudwatch-agent.service.
```

CloudWatch Agentのステータスを確認します。
※systemctl status amazon-cloudwatch-agentでも可
```
[root@ip-192-168-100-7 etc]# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a status
{
  "status": "running",
  "starttime": "2025-05-10T01:37:58+00:00",
  "configstatus": "configured",
  "version": "1.300055.0b1095"
}
```

雑な確認ですが、CloudWatchに出力されていますね。以上
![image (3).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/b01286f6-1caf-484c-af1b-a85802b84d85.png)
![image (4).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/182b1f14-fec9-4f41-b735-14c3276231d3.png)
![image (5).png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3219385/25970193-c9fc-4d81-8fbb-f0f68fb65d36.png)