Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Created January 4, 2017 16:41
Show Gist options
  • Save hagbarddenstore/037376bc3f7bdd7c9fa10c23f9fc95a1 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/037376bc3f7bdd7c9fa10c23f9fc95a1 to your computer and use it in GitHub Desktop.
from __future__ import print_function
import json
import boto3
import os
def lambda_handler(event, context):
instance_id = event.get("detail", {}).get("instance-id", "")
if instance_id == "":
print("Empty instance id")
return
print("Instance id: " + instance_id)
ec2 = boto3.resource("ec2")
instance = ec2.Instance(instance_id)
name = ""
for tag in instance.tags:
if tag.get("Key", "") == "Name":
name = tag.get("Value")
warn_statuses = [
"stopping",
"shutting-down"
]
state = event.get("detail", {}).get("state", "")
if state in warn_statuses:
sns = boto3.client("sns")
message = {
"event_type": "trigger",
"description": "Instance %s is %s" % (instance_id, state),
"details": {
"instance_id": instance_id,
"name": name
}
}
sns.publish(
TopicArn=os.environ.get("SNS_TOPIC", ""),
Message=json.dumps(message))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment