Extracting EC2InstanceId from SNS / SQS Autoscaling Message

I am using python Boto3 code, when the instance finishes from Auto Scaling group, it notifies SNS which is posting a message to SQS. Lambda is also triggered when SNS is notified, which runs a boto script to grab a message from SQS.

I am using the reference code from Sending and Receiving Messages in SQS Amazon .

Here's a snippet of code:

if messages.get('Messages'):
  m = messages.get('Messages')[0]
  body = m['Body']

  print('Received and deleted message: %s' % body)

      

Result:

START RequestId: 1234-xxxxxxxx Version: $LATEST
 {
  "Type" : "Notification",
  "MessageId" : "d1234xxxxxx",
  "TopicArn" : "arn:aws:sns:us-east-1:xxxxxxxxxx:AutoScale-Topic",
  "Subject" : "Auto Scaling: termination for group \"ASG\"",
  "Message" : "{\"Progress\":50,\"AccountId\":\"xxxxxxxxx\",\"Description\":\"Terminating EC2 instance: i-123456\",\"RequestId\":\"db-xxxxx\",\"EndTime\":\"2017-07-13T22:17:19.678Z\",\"AutoScalingGroupARN\":\"arn:aws:autoscaling:us-east-1:360695249386:autoScalingGroup:fef71649-b184xxxxxx:autoScalingGroupName/ASG\",\"ActivityId\":\"db123xx\",\"EC2InstanceId\":\"i-123456\",\"StatusCode\"\"}",
  "Timestamp" : "2017-07-",
  "SignatureVersion" : "1",
  "Signature" : "",
  "SigningCertURL" : "https://sns.us-east-1.amazonaws.com/..",
  "UnsubscribeURL" : "https://sns.us-east-1.amazonaws.com/
}

      

I only need the EC2InstanceId

completed instance, not the whole message. How can I extract the ID?

+3


source to share


2 answers


If your goal is to execute an AWS Lambda function (with an EC2 instance ID as a parameter), you also don't need to post the message to the Amazon SQS queue . This would actually be unreliable, because you cannot guarantee that the message received from the SQS queue matches the call to your lambda function.

Fortunately, when Auto Scaling sends SNS and SNS events, it triggers the Lambda function, SNS passes the necessary information directly to the Lambda function.

Start your Lambda with this code (or similar):



def lambda_handler(event, context):

    # Dump the event to the log, for debugging purposes
    print("Received event: " + json.dumps(event, indent=2))

    # Extract the EC2 instance ID from the Auto Scaling event notification
    message = event['Records'][0]['Sns']['Message']
    autoscalingInfo = json.loads(message)
    ec2InstanceId = autoscalingInfo['EC2InstanceId']

      

Then your code has an EC2 instance id without using Amazon SQS.

+2


source


Instance ID is in the message. This is raw JSON, so you can parse it with the package json

and get the information.



import json
if messages.get('Messages'):
  m = messages.get('Messages')[0]
  body = m['Body']
  notification_message = json.loads(body["Message"])

  print('instance id is: %s' % notification_message["EC2InstanceId"])

      

0


source







All Articles