I have lambda function to create new AMI and attach to current auto scale group. This function complete works when I create a test custom test case and pass the payload. Issue occurs when I trigger this from SNS:
import json
import boto3
import time
import sys
asObj = boto3.client('autoscaling')
ec2Obj = boto3.client('ec2')
def lambda_handler(event, context):
targetASG = event[‘Records’][0][‘Sns’][‘Message’]
ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[event['targetASG']])
sourceInstanceId = ASG.get('AutoScalingGroups')[0]['Instances'][0]['InstanceId']
Date=time.strftime("%d%m%y")
Time=time.strftime("%H%M%S")
amiName = "Automated_%s_%s" % (Date, Time)
configName = "Automated_%s_%s" % (Date, Time)
CreateNewImage = ec2Obj.create_image(
InstanceId = sourceInstanceId,
Name = amiName,
Description = 'Automatically Created Image from Lambda Service',
NoReboot = True)
Image = []
Image.append(CreateNewImage)
def getCreatedID(Image):
for i in Image:
ID = i['ImageId']
return ID
AMINewID = getCreatedID(Image)
CreateNewConfig = asObj.create_launch_configuration(
LaunchConfigurationName = configName,
ImageId = AMINewID,
InstanceId = sourceInstanceId)
updateASG = asObj.update_auto_scaling_group(
AutoScalingGroupName = event['targetASG'],
LaunchConfigurationName = configName)
return 'A new AMI has been Created `%s` Updated ASG `%s` with new launch configuration `%s` which includes AMI `%s`.' % (amiName,event['targetASG'], configName, AMINewID)
To trigger my lambda function I use AWS SNS topic and I publish a msg following message, message type: raw
{ "targetASG": "pre-production-xxx" }
But I get this error:
'targetASG': KeyError Traceback (most recent call last): File "/var/task/lambda_function.py", line 13, in lambda_handler ASG = asObj.describe_auto_scaling_groups(AutoScalingGroupNames=[event['targetASG']]) KeyError: 'targetASG'
How can I resolve this?