序章
空き容量をCloudWatchに通知・アラート設定する方法は世に出回っているけど、これインスタンス変えたらメトリックスも変わっちゃうからインスタンスが変わるたびにアラート設定が消える?(気がする。)
EC2インスタンスにcron仕掛けるしかない(気がする。)
ということで今回は、お手製のシェルスクリプトでディスク使用率が大きくなったらSNS経由でメールを送って優勝していくことにするわね。
とっくん26歳風
https://www.youtube.com/watch?v=wtinMFr_uxs
シェルのコード
EC2のどこかにシェルを潜影蛇手!
#!/bin/sh
#アラート閾値(%)
threshold=95
#送信元SNS
sns_topic_arn="arn:aws:sns:*************"
#dfコマンドの結果を取得、Used列の数値の部分だけ取得
lines=`df -h|sed -e 's/[ \t][ \t]*/ /g'|cut -d ' ' -f 5|sed -e 's/%//g'|grep -e "[0-9]"|bc`
while read line
do
#もし閾値を超えていたら
if [ $line -gt ${threshold} ]; then
#Instance Id
id=`curl -s 'http://169.254.169.254/latest/meta-data/instance-id'; echo -en "\n"`
#インスタンスのタグ
tag=`aws ec2 describe-instances --region ap-northeast-1 --instance-id ${id} --query 'Reservations[].Instances[].Tags[].Value[]' | grep [0-9a-zA-Z] | sed 's/^.*"\(.*\)".*$/\1/'`
#インスタンスのIP
ip=`aws ec2 describe-instances --region ap-northeast-1 --instance-id ${id} --query 'Reservations[].Instances[].PrivateIpAddress' | grep [0-9a-zA-Z] | sed 's/^.*"\(.*\)".*$/\1/'`
#dfコマンド結果
df=`df -h`
#メール本文に改行を入れたいので改行を入れて対応(雑)
body="id:${id}
ip:${ip}
tag:${tag}
df:-----
${df}"
#送信!!
aws sns publish --region ap-northeast-1 --topic-arn "${sns_topic_arn}" --message "${body}" --subject "${ip}のディスク使用率が${threshold}%を超えました。"
fi
done << END
$lines
END
リージョンとかは適宜変更してくださいね。
動くことを確認したらcrontab に潜影蛇手!
まとめ
メモリとかディスク容量とか何もしないでもCloudWatchに自動的に送ってくれるようになったらいいのに。
キーワード
空き容量 アラート EC2 インスタンスID インスタンスのIP SNS
変更点
2020.03.17
・ルートディレクトリだけでなくすべてのディレクトリ/パーティションがチェック対象になるように修正