🦔

セキュリティグループを入れ替えるLambda

に公開
import boto3

ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    # ✅ 削除/追加するセキュリティグループID
    sg_to_remove = 'sg-072703eb48616d104'
    sg_to_add = 'sg-0e7d546d94fd21d6a'

    # "Name"タグに"test"を含むインスタンスをフィルタ
    response = ec2.describe_instances(
        Filters=[
            {'Name': 'tag:Name', 'Values': ['*test*']},
            {'Name': 'instance-state-name', 'Values': ['running', 'stopped']}
        ]
    )

    # 該当インスタンス一覧取得
    instances = []
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instances.append(instance)

    if not instances:
        return {"status": "No EC2 instance with 'test' in Name tag found."}

    # 起動時間で最新のインスタンスを選ぶ
    latest_instance = sorted(instances, key=lambda x: x['LaunchTime'], reverse=True)[0]
    instance_id = latest_instance['InstanceId']

    # 最初のENIを取得
    eni = latest_instance['NetworkInterfaces'][0]
    eni_id = eni['NetworkInterfaceId']
    current_sgs = eni['Groups']
    current_sg_ids = [sg['GroupId'] for sg in current_sgs]

    # セキュリティグループ削除
    updated_sg_ids = [sg for sg in current_sg_ids if sg != sg_to_remove]

    # セキュリティグループ追加(まだ付いていなければ)
    if sg_to_add not in updated_sg_ids:
        updated_sg_ids.append(sg_to_add)

    # 少なくとも1つSGが必要
    if not updated_sg_ids:
        return {"status": "Error: Cannot remove all security groups. At least one SG is required."}

    # ENIのセキュリティグループを更新
    ec2.modify_network_interface_attribute(
        NetworkInterfaceId=eni_id,
        Groups=updated_sg_ids
    )

    return {
        "status": "Success",
        "instance_id": instance_id,
        "removed_sg": sg_to_remove,
        "added_sg": sg_to_add,
        "final_sg_list": updated_sg_ids
    }

Discussion