从SNS / SQS Auto Scaling消息中提取EC2InstanceId

时间:2017-07-18 00:52:09

标签: amazon-web-services amazon-sqs boto3 autoscaling

我使用python Boto3代码,当一个实例从Auto Scaling组终止时,它会通知SNS将消息发布到SQS。通知SNS时也会触发Lambda,执行boto脚本以从SQS获取消息。

我正在使用Sending and Receiving Messages in Amazon SQS中的参考代码。

以下是代码段:

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

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

结果是:

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/
}

我只需要终止实例的EC2InstanceId而不是整个消息。我该如何提取ID?

2 个答案:

答案 0 :(得分:2)

如果您的目标是执行AWS Lambda函数(将EC2实例ID作为参数),则也不需要将消息发布到Amazon SQS队列。实际上,这是不可靠的,因为您不能保证从SQS队列中检索的消息与您的Lambda函数的调用匹配。

幸运的是,当Auto Scaling向SNS和SNS发送事件然后触发Lambda函数时,SNS 将必要的信息直接传递给Lambda函数。

使用此代码(或类似代码)启动Lambda函数:

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']

您的代码将拥有EC2实例ID,而无需使用Amazon SQS。

答案 1 :(得分:0)

实例ID在邮件中。它是原始JSON,因此您可以使用json包解析它并获取信息。

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"])