AWS上に複数人が利用する開発用サーバを立てました。24時間365日稼働させる必要はありませんが、手作業で起動・停止を行うのも馬鹿げています。
そこで、業務時間外に対象インスタンスを停止し、始業前に対象インスタンスを開始するスクリプトを書いて、NATインスタンス上のcronで実行してみました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ sudo cat /etc/cron.d/ec2-cost-saving.sh | |
#!/bin/sh | |
# USAGE : ./ec2-cost-saving.sh [instance-id] [start/stop] | |
INSTANCE_ID="${1}" | |
ACTION="${2}" | |
INSTANCE_STATE=`aws ec2 describe-instances --instance-ids "${INSTANCE_ID}" | jq ' .Reservations[].Instances[].State.Name'` | |
case ${ACTION} in | |
'start' ) | |
case ${INSTANCE_STATE} in | |
'"stopped"' ) | |
aws ec2 start-instances --instance-ids "$INSTANCE_ID" | |
;; | |
'"running"' ) | |
echo "${INSTANCE_ID} is already running" | |
;; | |
esac | |
;; | |
'stop' ) | |
case ${INSTANCE_STATE} in | |
'"stopped"' ) | |
echo "${INSTANCE_ID} is already stopped" | |
;; | |
'"running"' ) | |
aws ec2 stop-instances --instance-ids "$INSTANCE_ID" | |
;; | |
esac | |
;; | |
esac | |
$ sudo cat /etc/cron.d/ec2-cost-save | |
#!/bin/sh | |
30 22 * * * ec2-user /home/ec2-user/ec2-cost-saving.sh i-xxxxxxxx stop | |
0 8 * * * ec2-user /home/ec2-user/ec2-cost-saving.sh i-xxxxxxxx start |
ちゃんと動いていますが、以下の様な点を修正する必要がありますね。
- AWS CLIの実行結果が標準出力となり、ec2-userにメールが届いてしまう
- 万が一起動に失敗した場合、他のメンバーに迷惑がかかるので、メール通知したい。