LoginSignup
1
1

More than 5 years have passed since last update.

CloudWatch LogsでEC2インスタンスのタグで設定した名前を使うためのスクリプト

Posted at

もともとは下記のような設定ファイルとなっています。

/etc/awslogs/awslogs.conf
[/var/log/messages]
file = /var/log/messages
log_group_name = /var/log/messages
log_stream_name = {instance_id}
datetime_format = %Y-%m-%d %H:%M:%S

変数 {instance_id}と記載していれば、自分自身のインスタンスIDが設定されるようになるのですが、logsの一覧で見たときに、「あれ?自分のみたいインスタンスはどれだっけ・・・」みたいになります。

ですが、設定ファイル自体に固定で埋め込んでいるとAnsibleのようなツールを使う場合は結構面倒。
なので、自分自身のメタデータ取得とインスタンス情報取得の組み合わせでタグに設定している「Name」を取得するように設定します。

rename_log_stream_name.sh
#!/bin/sh

INSTANCEID=`curl -s http://169.254.169.254/latest/meta-data/instance-id/`
Name=`aws ec2 describe-instances --instance-ids ${INSTANCEID} --region ap-northeast-1 --output text --query 'Reservations[].Instances[].Tags[?Key==\`Name\`].[Value]'`

sed -i -e "s/{instance_id}/${Name}/g" /etc/awslogs/awslogs.conf

Ansibleだとこんな感じに設定できます。

role/awslogs/tasks/main.yml
- name: install awslogs
  yum: name=awslogs state=latest

- name: Configure awscli.conf
  template: src=awscli.conf.j2 owner=root dest=/etc/awslogs/awscli.conf

- name: Configure awslogs.conf
  template:
    dest: /etc/awslogs/awslogs.conf
    group: root
    mode: 0644
    owner: root
    src: awslogs.conf.j2
  notify: restart awslogs agent

- name: インスタンスID置換スクリプト
  shell: /home/ec2-user/rename_log_stream_name.sh
  notify: restart awslogs agent
1
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
1
1