LoginSignup
3
5

More than 5 years have passed since last update.

EC2インスタンスをスケジュールで起動、停止させる

Last updated at Posted at 2017-10-29

EC2インスタンスをスケジュールで起動、停止させる

目的

  1. lamdbaについて勉強したい
  2. インスタンスの停止忘れを無くしたい
  3. Pythonについて知りたい

関数作成 その1

関数名とロールを設定する。

  • 名前
    • myStartStopEC2Instances
  • ロール
    • カスタムロール作成

カスタムロールの作成を選択すると、カスタムロール作成の新規画面が開く

Screenshot 2017-10-28_20-09-37.png

カスタムロールの作成

  • ロール名
    • 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": "*"
    }
  ]
}    

Screenshot 2017-10-28_20-12-34.png

関数作成 その2

作成したロールが既存のロールとして読み込まれているので、[関数の作成]を行う。

Screenshot 2017-10-28_20-13-10.png

  • ランタイム
    • 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つのインスタンスに対して起動を指示してみます。

Screenshot 2017-10-28_20-38-06.png

インスタンスIDは任意のIDに変更
対象を3つ定義しているが、当然増減させて良い

  • イベント名
    • TestStartEC2
test.json
{
 "Action": "start",
 "Region": "ap-northeast-1", 
 "Instances":
  [
   "i-xxxxxxxxxxxxxxxxx",
   "i-yyyyyyyyyyyyyyyyyy",
   "i-zzzzzzzzzzzzzzzzz"
  ]
}

Screenshot 2017-10-28_20-19-54.png

動作テスト

EC2インスタンスが起動するか、動作確認を行います。
実行結果が成功となり、EC2が起動していればOKです。

Screenshot 2017-10-28_20-20-28.png

Screenshot 2017-10-28_20-20-55.png

CloudWatch

  • 名前
    • DailyStopEC2
  • イベントソース
    • Cron式
      • 毎日 23:30
      • 画像ではJSTで23:30を指定していますが、GMTに変換する必要があります
      • 30 14 * * ? *
  • ターゲット
    • 機能
      • myStartStop_EC2_instances
    • 入力
      • 定数(JSON テキスト)
      • Action,Region,Instancesは対象に合わせて設定
      • {"Action": "stop", "Region": "ap-northeast-1", "Instances": ["i-xxxxxxxxxxxxxxxxx","i-yyyyyyyyyyyyyyyyyy","i-zzzzzzzzzzzzzzzzz"]}

Image 002.png
Image 003.png

参考

3
5
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
3
5