EC2インスタンスをスケジュールで起動、停止させる
目的
- lamdbaについて勉強したい
- インスタンスの停止忘れを無くしたい
- Pythonについて知りたい
関数作成 その1
関数名とロールを設定する。
- 名前
- myStartStopEC2Instances
- ロール
- カスタムロール作成
カスタムロールの作成を選択すると、カスタムロール作成の新規画面が開く
カスタムロールの作成
- ロール名
- myStartStop_EC2_Instances
- ポリシードキュメント
- EC2の起動、停止を許可
ポリシードキュメント
{
"Version": "2012-10-17",
"Statement": [![Screenshot 2017-10-28_20-38-06.png](https://qiita-image-store.s3.amazonaws.com/0/88753/6aee1997-0196-ebb1-303b-d52803d52427.png)
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
関数作成 その2
作成したロールが既存のロールとして読み込まれているので、[関数の作成]を行う。
- ランタイム
- Python 2.7
- コード
- lambda_function.py
- ハンドラ
- lambda_function.lamdbda_handler
lambda_handler.py
import boto3
def lambda_handler(event, context):
region = event['Region']
instances = event['Instances']
ec2 = boto3.client('ec2', region_name=region)
if event['Action'] == 'start':
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + ", ".join(instances)
elif event['Action'] == 'stop':
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + ", ".join(instances)
動作テスト
任意のパラメータを設定して、動作を確認する。
3つのインスタンスに対して起動を指示してみます。
インスタンスIDは任意のIDに変更
対象を3つ定義しているが、当然増減させて良い
- イベント名
- TestStartEC2
test.json
{
"Action": "start",
"Region": "ap-northeast-1",
"Instances":
[
"i-xxxxxxxxxxxxxxxxx",
"i-yyyyyyyyyyyyyyyyyy",
"i-zzzzzzzzzzzzzzzzz"
]
}
動作テスト
EC2インスタンスが起動するか、動作確認を行います。
実行結果が成功となり、EC2が起動していればOKです。
CloudWatch
- 名前
- DailyStopEC2
- イベントソース
- Cron式
- 毎日 23:30
- 画像ではJSTで23:30を指定していますが、GMTに変換する必要があります
30 14 * * ? *
- Cron式
- ターゲット
- 機能
- myStartStop_EC2_instances
- 入力
- 定数(JSON テキスト)
- Action,Region,Instancesは対象に合わせて設定
{"Action": "stop", "Region": "ap-northeast-1", "Instances": ["i-xxxxxxxxxxxxxxxxx","i-yyyyyyyyyyyyyyyyyy","i-zzzzzzzzzzzzzzzzz"]}
- 機能
参考
- 超参考に...というかやっていることそのまま