LoginSignup
0
0

More than 5 years have passed since last update.

Tagで指定した時間にインスタンスを止める(AWS EC2)

Last updated at Posted at 2019-04-08

お金を無駄にしたくないので、タグで時間を設定しておいて、その時間が来たら停止するようなスクリプトを作りました。

事前設定

EC2のタグでshutdown_timeタグを作成し、値に0~23までの数字を入力

管理サーバを用意。
(サーバ内にaws-cliのセットアップを行う)

スクリプト

#!/bin/sh

#現在のhourを取得
CURRENT_HOUR=`date | awk '{print $4}' | awk -F '[:]' '{print $1}'`

#起動中インスタンスの中からshutdown_timeタグに設定した時間と現在の時間が一致してたら停止
aws ec2 stop-instances --instance-ids\ 
$(/usr/local/bin/aws ec2 describe-instances | jq -r '[.Reservations[].Instances[] | select((.State.Name == "running") and (.Tags != null) and (.Tags[] | select(.Key == "shutdown_time") | .Value == "'$CURRENT_HOUR'")) | .InstanceId] | join(" ")')

このスクリプトを保存し、cronを設定

#毎時シェル実行
0 */1 * * * start_instances.sh

参考
https://teratail.com/questions/111679
https://shellscript.sunone.me/variable.html

余談
Lambdaでも十分できそう。
これだとタグつけてないと起動しっぱなしになるので、ないときは勝手に落とすようなスクリプトor Lambdaを書く予定。

0
0
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
0