For each AWS region
1.Get all EC2 instances that either
2.are Tagged with tag Owner and value Unknown or unknown
3.are missing tag Owner
For each EC2 instance
4.Check if the instance has a tag "Terminate_On"
Else
5.Tag the instance with a tag "Terminate_On" and value of the date 7 days from now.
steps 1,2 and 3 are completed:
import boto3
import collections
import datetime
import time
import sys
from datetime import datetime
from dateutil.relativedelta import relativedelta
ec = boto3.client('ec2', 'eu-west-1')
ec2 = boto3.resource('ec2', 'eu-west-1')
date_after_month = datetime.now()+ relativedelta(days=7)
#print date_after_month.strftime('%d/%m/%Y')
def lambda_handler(event, context):
reservations = ec.describe_instances().get('Reservations', [])
for reservation in reservations:
for instance in reservation['Instances']:
tags = {}
for tag in instance['Tags']:
tags[tag['Key']] = tag['Value']
if not 'Owner' in tags:
a = instance['InstanceId'] + " does not have Owner tag"
elif tags['Owner'] in ['Unknown', 'unknown']:
b = instance['InstanceId'] + " has [U|u]nknown Owner tag"
if not 'TerminateOn' in tags:
ec2.create_tags(
Resources=[instance['InstanceId']],
Tags= [{
'Key':'TerminateOn',
'Value':date_after_month.strftime('%d/%m/%Y')}])
#print a+" "+b
4.for instances returned from above code (Instances with Owner tags and instances without owner tag) check if Terminate_On
tag exists
5.if not, create that tag with date_after_month.strftime('%d/%m/%Y')
as value
The issues is on step 5, if one EC2 instance is running, no problem, tag is created, but if more than one, then tag is created only for first one
and following error is shown:
for tag in instance['Tags']:
KeyError: 'Tags'
instance
variable – FelixEnescu