概要
AWS lambdaでEC2の起動があるかチェックするスクリプトです。 停止忘れによる課金防止チェックに利用できます。
スクリプト
lamdba(python)
import json
import botocore
import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    response = client.describe_instances()
    for resp in response['Reservations']:
        for inst in resp['Instances']:
            instance_status = inst['State']['Name']
            instance_name = [tag['Value'] for tag in inst['Tags'] if tag['Key'] == 'Name'][0]
        if not instance_status == "stopped":
            print("alert!")
            #「not stopped」の文言をクラウドウオッチで検知させる
            print(f"instance not stopped.({instance_name} is {instance_status})")
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('OK!')
    }
関連構成案
起動トリガー:eventBridgeからスケジュール起動 検知方式:cloudWatchからログに「not stopped」がある場合アラートとする
 折りたたみ
 折りたたみ 展開
 展開