1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS EC2 インスタンスタイプの一括自動更新

Last updated at Posted at 2022-10-18

TODO

  • EC2のイベント対応で夜間に自動停止・起動
  • インスタンスタイプを夜間に自動更新

内容

tag

  • Key=Schedule, Value= [1:予約あり, 0:予約実行完了]
  • オプション
    例)t3.microに変更
    Key=InstanceType, Value=t3.micro

EventBridge

  • 例)毎週木曜日0時に処理
    cron(0 15 ? * WED *)

Lambda

lambda_handler Python3.9
import boto3
import json
import pprint

def lambda_handler(event, context):
    cnt = 0
    log_msg = []
    task_tag = 'Schedule'

    client = boto3.client('ec2')
    reservations = client.describe_instances(
        Filters=[{
            'Name': f'tag:{task_tag}',
            'Values': ['1']
        }]
    )

    for reservation in reservations['Reservations']:
        for instance in reservation['Instances']:
            cnt = cnt + 1
            new_instance_type = ''
            inst_id = instance['InstanceId']
            instance_type = instance['InstanceType']
            state_name = instance['State']['Name']

            for tag in instance['Tags']:
                if tag['Key'] == 'InstanceType':
                    new_instance_type = tag['Value']
                    break

            log_msg.append(f"{inst_id}, {state_name}, {instance_type}, {new_instance_type}")

            if state_name == 'running':
                response = client.stop_instances(InstanceIds=[inst_id])
                log_msg.extend(response)
                
                #停止まで待機
                waiter = client.get_waiter('instance_stopped')
                waiter.wait(InstanceIds=[inst_id])

            #インスタンスタイプ変更があると処理
            if new_instance_type and new_instance_type != instance_type:
                response = client.modify_instance_attribute(InstanceId=inst_id, Attribute='instanceType', Value=new_instance_type)

            #重複処理防止のため、処理完了とのタグ値更新
            response_tag = client.delete_tags(
                Resources=[inst_id],
                Tags=[{'Key': task_tag, 'Value': '1'}],
            )
            response_tag = client.create_tags(
                Resources=[inst_id],
                Tags=[{'Key': task_tag, 'Value': '0'}],
            )
            log_msg.extend(response_tag)

            response = client.start_instances(InstanceIds=[inst_id])
            log_msg.extend(response)

    log_msg.append(f'instance count: {cnt}')
    pprint.pprint(log_msg)

    return {
        'statusCode': 200,
        'body': json.dumps('ok')
    }

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?