概要
EC2インスタンスのシャットダウンをトリガーに、何か処理を実行する方法を記します。
今回はS3に辞世の句を投稿していますが、AutoScalingでterminateされるEC2のlocalのsyslogをS3に転送する等の処理にも応用できます。
やり方
1.S3にバケットを作成する
S3のバケット名はFQDNにしておくと色々捗る(余談)
2.S3にフルアクセスできるIAMを作成する
アクセスキーIDとシークレットアクセスキーは後で使うのでメモ帳にコピペしといてください
3.AWS CLIをインストールする
※Amazon Linuxの場合は不要です
//pipのインストール
# curl -O https://bootstrap.pypa.io/get-pip.py
//Python を使用してスクリプトを実行
# python get-pip.py --user
//PATH 変数に実行可能パスを追加
# export PATH=~/.local/bin:$PATH
# source ~/.bash_profile
//pipが正しくインストールされたことを確認
# pip --version
//pip を使用して AWS CLI をインストール
# pip install awscli --upgrade --user
//AWS CLI が正しくインストールされたことを確認
# aws --version
2.AWS CLIの初期設定をする
# aws configure
AWS Access Key ID [None]: [アクセスキーID]
AWS Secret Access Key [None]: [シークレットアクセスキー]
Default region name [None]: [空でok]
Default output format [None]:[空でok]
3.辞世の句スクリプトを作成する
# vim /etc/rc.d/init.d/DeathPoem.sh
/etc/rc.d/init.d/DeathPoem.sh
#!/bin/sh
InstanceId=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`
declare logdir=/var/www/log
declare log=/death_poem.log
declare bucket=files.hoge.com
declare now=`date +'%Y-%m-%d'`
declare s3_target="s3://${bucket}/death_poem_${now}/"
mkdir $logdir >/dev/null 2>&1
printf 'I am '$InstanceId'¥n' >> $logdir$log
printf 'I was born 'date --date=@$(expr `date +%s` - `cut -d "." -f 1 /proc/uptime`) >> $logdir$log
printf 'I was just 'cat /proc/uptime | awk '{print $1 / 60 /60 /24 "days (" $1 "sec)"}' | tr -d '¥n'' from birth ''¥n' >> $logdir$log
printf 'I will die 'date'¥n¥n' >> $logdir$log
aws s3 sync $logdir $s3_target
4.辞世の句スクリプトに実行権限を与える
# chmod 755 /etc/rc.d/init.d/DeathPoem.sh
5.rc.local(起動時実行)を編集する
# vim /etc/rc.d/rc.local
/etc/rc.d/rc.local
#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
touch /var/lock/subsys/local
/sbin/ethtool -s eth0 wol g
touch /var/lock/subsys/DeathPoem
ln -s /etc/init.d/DeathPoem.sh /etc/rc0.d/K00DeathPoem
ln -s /etc/init.d/DeathPoem.sh /etc/rc6.d/K00DeathPoem
6.EC2インスタンスを再起動する
# reboot
7.ログを確認する
# tailf /var/www/log/death_poem.log
/var/www/log/death_poem.log
I am i-************
I was born Mon Sep 11 04:00:48 UTC 2017
I was just 0.00817488days (706.31sec) from birth
I will die Mon Sep 11 04:12:34 UTC 2017
8.S3のバケットを確認する
上記と同じ内容の辞世の句が投稿されているはず!
余談
昔は簡単だった(らしい)
EC2で起動時やterminate時にシェルを実行する | Developers.IO
mytest.sh
#!/bin/sh
# chkconfig: 2345 99 10
# description: test shell
case "$1" in
start)
echo "start!" > /path/your/start.txt
;;
stop)
echo "stop!" > /path/your/stop.txt
;;
*) break ;;
esac
あのクラスメソッドさんが書いた記事なら間違いない!
…と思っていたのですが、上記の方法では"start"のイベントしか取得できませんでした。
コメントにあったprocessnameを追加しても結果は同様でした。
原因をご存じの方いたらぜひ教えて欲しいです
とても参考になった文献
CentOS6.0 Shutdown時にコマンド実行 : 事象の水平線 :