LoginSignup
6
2

More than 5 years have passed since last update.

LambdaでのEC2起動停止にタグを利用する

Last updated at Posted at 2017-05-04

Pyhoneを使って、LambdaでEC2の起動停止をタグで制御する覚書です。

以前は、インスタンスIDを直接指定してしまっていたのですが、
インスタンスが増えてきたという理由もあり、管理も大変になってきた為に、
タグで制御するようにしてみました。

Lambdaで言語はPython2.7を選択して下記スクリプトを記載。

import boto3

def lambda_handler(event, context):

    # リージョンを指定
    ec2 = boto3.client('ec2', "ap-northeast-1")
    resp = ec2.describe_instances()
    targets = []
    for reservation in resp['Reservations']:
      for instance in reservation['Instances']:
        if 'Tags' in instance:
            for tag in instance['Tags']:

                # タグが isSchedule の場合に、値が true を対象
                if tag['Key'] == 'isSchedule' and tag['Value'] == 'true':
                    targets.append(instance['InstanceId'])

    if len(targets) > 0:
        ec2.start_instances(InstanceIds=targets)
        print 'started instances: ' + str(targets)

例外とかはきちんと処理してログ出したほうがいいのかな。

終了させる場合は、最後から2行目を下記に変更。
ec2.stop_instances(InstanceIds=targets)

6
2
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
6
2