Skip to content

Instantly share code, notes, and snippets.

@acumenix
Forked from kangks/ec2TagCheck.py
Created August 23, 2019 06:26
Show Gist options
  • Save acumenix/590995db9c2ed964a96061b4080c3729 to your computer and use it in GitHub Desktop.
Save acumenix/590995db9c2ed964a96061b4080c3729 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 = '[email protected]'
ses_destination = ['[email protected]']
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