Skip to content

Instantly share code, notes, and snippets.

@polomarcus
Created January 10, 2020 14:40
Show Gist options
  • Save polomarcus/a4f6ee55fe515044c02ba705f4e94baf to your computer and use it in GitHub Desktop.
Save polomarcus/a4f6ee55fe515044c02ba705f4e94baf to your computer and use it in GitHub Desktop.
Graceful shutdown using Simple Sytems Manager and Terraform on AWS
def lambda_handler(event, context):
for record in event['Records']:
parsed_event = (json.loads(record["body"]))
msg_receipt_handle = str(record['receiptHandle'])
if parsed_event.get("LifecycleTransition") == "autoscaling:EC2_INSTANCE_TERMINATING" and parsed_event.get("LifecycleHookName") == "my-service":
auto_scaling_group = get_env_variable('ASG_NAME').split()[0]
ec2_instance_id = parsed_event.get("EC2InstanceId")
delete_sqs_message(msg_receipt_handle) # delete first to avoid infinite loop on unvalid instance ID
ssm_command([ec2_instance_id]) # must be an array
else:
print "not a EC2_INSTANCE_TERMINATING event - skipping lambda"
delete_sqs_message(msg_receipt_handle)
@91vikash
Copy link

91vikash commented Oct 19, 2020

parsed_event.get not returns anything.. as json that it parses has a nested formatted..How to extract the data...

parsed_eventt.get("LifecycleTransition") returns null as LifecycleTransition is inside detail
{
   "version":"0",
   "id":"2a56d3fd-c725-783c-149b-828e896dd407",
   "detail-type":"EC2 Instance-terminate Lifecycle Action",
   "source":"aws.autoscaling",
   "account":"xxxxx",
   "time":"2020-10-19T16:21:22Z",
   "region":"eu-central-1",
   "resources":[
      "arn:aws:autoscaling:eu-central-1:xxxxx:autoScalingGroup:21e4d916-4802-4dfe-90e9-e9b07b3f71af:autoScalingGroupName/xxx"
   ],
   "detail":{
      "LifecycleActionToken":"afe0cde4-c2aa-4881-9c58-c57c2e67ff7f",
      "AutoScalingGroupName":"xxx",
      "LifecycleHookName":"gracefulShutDownQueue",
      "EC2InstanceId":"i-053227e06596054e8",
      "LifecycleTransition":"autoscaling:EC2_INSTANCE_TERMINATING"
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment