0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWSでEC2:AmazonLinux2023のログをCloudWatchに転送する

Posted at

EC2に構築したAmazonLinux2023のログ(messagesとsecure)を
Cloudwatchに転送する手順を整理(備忘録)。

1. EC2にIAMロールを適用する

IAMロールを作成して「CloudWatchAgentServerPolicy」を割り当てる。
作成したIAMロールをEC2に適用する。

2.rsyslogのインストール・設定

※AmazonLinux2023 はデフォルトで /var/log/messages が無いので、
rsyslog を入れて従来型のログファイルを出力できるようにする。

sudo dnf install -y rsyslog
sudo systemctl enable rsyslog
sudo systemctl start rsyslog

確認
ls -l /var/log/messages /var/log/secure

テストログの出力
logger "test from AL2023"
tail -n 5 /var/log/messages

3.CloudWatchのインストール

Amazon Linux 2023 なら公式リポジトリからインストールする。
sudo dnf install -y amazon-cloudwatch-agent

バージョン確認
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -version
#CWAgent/1.3000... みたいな表示ならOK

4.CloudWatchの設定

/opt/aws/amazon-cloudwatch-agent/bin/config.jsonを新規作成

設定内容:
・file_path:収集対象のログファイル
・log_group_name:CloudWatch Logs のロググループ名(自動作成される)
・log_stream_name: {instance_id} にしておくとインスタンスごとにストリーム分割
・retention_in_days: 90 で 3か月保持

{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          {
            "file_path": "/var/log/messages",
            "log_group_name": "/ec2/al2023/messages",
            "log_stream_name": "{instance_id}",
            "retention_in_days": 90
          },
          {
            "file_path": "/var/log/secure",
            "log_group_name": "/ec2/al2023/secure",
            "log_stream_name": "{instance_id}",
            "retention_in_days": 90
          }
        ]
      }
    }
  }
}

5.設定を CloudWatch Agent に読み込ませて起動

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
  -a fetch-config -m ec2 \
  -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json \
  -s

サービス状態の確認
sudo systemctl status amazon-cloudwatch-agent

※起動していない場合は下記を実行する
sudo systemctl start amazon-cloudwatch-agent
sudo systemctl enable amazon-cloudwatch-agent

6.動作確認

・テストログを追加

logger "cloudwatch test from AL2023"

AWSマネジメントコンソール サービス → CloudWatch 左メニュー → ログ → ロググループ /ec2/al2023/messages と /ec2/al2023/secure が生成されているか確認

ロググループを開く → ログストリームを選択
→ 先ほどの "cloudwatch test from AL2023" が1〜3分以内に出ていれば OK
※ 反映まで 数分のタイムラグ があるのは正常です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?