I have following task:
1.Check if the instance has a tag "Terminate_On"
If yes:
2.Check if the instance should be terminated today
If yes:
3.Remove instance termination protection if enabled Terminate the instance
I'm stuck on part 3: don't know how to remove protection if enabled and to terminate instance
1.Check if the instance has a tag "Terminate_On"
If yes:
2.Check if the instance should be terminated today
If yes:
3.Remove instance termination protection if enabled Terminate the instance
I'm stuck on part 3: don't know how to remove protection if enabled and to terminate instance
import boto3 import collections import datetime import time import sys ec = boto3.client('ec2', 'eu-west-1') ec2 = boto3.resource('ec2', 'eu-west-1') from datetime import datetime from dateutil.relativedelta import relativedelta date_after_month = datetime.now()+ relativedelta(days=7) #print date_after_month.strftime('%d/%m/%Y') today=datetime.now().strftime('%d/%m/%Y') def lambda_handler(event, context): instance_ids = [] reservations = ec.describe_instances( Filters=[ {'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']}, ] ).get('Reservations', []) for reservation in reservations: instances = reservation['Instances'] for instance in instances: instance_ids.append(instance['InstanceId']) tags = {} for tag in instance['Tags']: tags[tag['Key']] = tag['Value'] if 'TerminateOn' in tags: if tags["TerminateOn"]==today: #remove termination protection if enabled #terminate instance else: print "No need for termination" if not 'TerminateOn' in tags: ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}]) print("Stopping instances: {}".format(','.join(instance_ids)))