Skip to content

Instantly share code, notes, and snippets.

@kangks
Created May 19, 2017 21:01
Show Gist options
  • Save kangks/6d99a157b4b1727e237286543e8412fe to your computer and use it in GitHub Desktop.
Save kangks/6d99a157b4b1727e237286543e8412fe to your computer and use it in GitHub Desktop.
Lambda function triggered by CloudTrail events to check for tagging, and notify the owner through SES if tagging not found
import boto3
required_keys = [ "key01", "key02", "key03", "key04" ]
ses_source = 'source@maildomain.com'
ses_destination = ['somebody@domain.com']
def lambda_handler(event, context):
if 'detail' in event and 'instance-id' in event['detail']:
ec2_instance_id = event['detail']['instance-id']
ec2 = boto3.resource('ec2')
instance = ec2.Instance(ec2_instance_id)
tags = instance.tags
all_keys = []
for tag in tags:
all_keys.append(tag['Key'])
missing=[]
for rk in required_keys:
if rk not in all_keys:
missing.append(rk)
if len(missing) > 0:
message = 'missing keys in EC2(ID:' + ec2_instance_id + '):' + ','.join(missing)
ses = boto3.client('ses')
response = ses.send_email(
Source=ses_source,
Destination={
'ToAddresses': ses_destination
},
Message={
'Subject': {
'Data': message,
'Charset': 'ascii'
},
'Body': {
'Text': {
'Data': message,
'Charset': 'ascii'
},
'Html': {
'Data': message,
'Charset': 'ascii'
}
}
},
ReplyToAddresses=[
ses_source,
],
ReturnPath=ses_source
)
return 'checked ' + ec2_instance_id + ', missing: ' + str(len(missing) > 0)
else:
return ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment