1
votes

I want that if state of my ec2 will change then I will receive a SNS and it contains ec2 name ,instance id and account name, region.

import boto3

def lambda_handler(event, context):

    # Extract Instance ID from event
    instance_id = event['detail']['instance-id']

    # Obtain information about the instance
    ec2_client = boto3.client('ec2')
    instance_info = ec2_client.describe_instances(InstanceIds=[instance_id])
    instance = instance_info['Reservations'][0]['Instances'][0]

    # Extract name tag
    name_tags = [t['Value'] for t in instance['Tags'] if t['Key']=='Name']
    name = name_tags[0] if name_tags is not None else ''

    # Send message to SNS
    MY_SNS_TOPIC_ARN = 'arn:aws:sns:ap-southeast-2:123456789012:foo'
    sns_client = boto3.client('sns')
    sns_client.publish(
        TopicArn = MY_SNS_TOPIC_ARN,
        Subject = 'Instance Change State: ' + instance_id,
        Message = 'Instance: ' + instance_id + ' has changed state\n' +
                  'State: ' + instance['State']['Name'] + '\n' +
                  'IP Address: ' + instance['PublicIpAddress'] + '\n' +
                  'Name: ' + name
    )

Getting below error...

START RequestId: 7c29aec4-2d51-4b29-91a0-8fc1217397ce Version: $LATEST 'detail': KeyError Traceback (most recent call last): File "/var/task/lambda_function.py", line 6, in lambda_handler instance_id = event['detail']['instance-id'] KeyError: 'detail'

1
How are you invoking the function? Did you create the CloudWatch Event as per Email notification through SNS and Lambda? It would appear that the function is not receiving event information from CloudWatch Events.John Rotenstein
Can you add print(event) at the beginning of your function handler and check the event object structure?Marcin

1 Answers

0
votes

Did you create the trigger by cloudwatch event and create cloudwatch event based on EC2 instance state-change?

At first glance, the event pattern preview is

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ]
}

So please check with above and give us more information about your case.