AWS Lambda to Disable EC2 termination protection

Posted: September 25, 2018 in AWS, Scripts

This code will list all EC2 instances for every region and if termination protection is enabled, it will be disabled

import json
import boto3
def lambda_handler(event, context):
  client = boto3.client('ec2')
  ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
  for region in ec2_regions:
     client = boto3.client('ec2', region_name=region)
     conn = boto3.resource('ec2',region_name=region)
     instances = conn.instances.filter()
     for instance in instances:
       if instance.state["Name"] == "running":
       #print instance.id # , instance.instance_type, region)
        terminate_protection=client.describe_instance_attribute(InstanceId =instance.id,Attribute = 'disableApiTermination')
        protection_value=(terminate_protection['DisableApiTermination']['Value'])
        if protection_value == True:
          client.modify_instance_attribute(InstanceId=instance.id,Attribute="disableApiTermination",Value= "False" )
Comments
  1. AWS Training says:

    Nice! Thanks for sharing this information

    Like

  2. Suresh Kumar says:

    Good post! Tried this at the beginning of last year but left it halfway since I didn’t have much time and also I overlooked describe_instance_attribute method. But this time I didn’t have to do the research 😀 Thank you!

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s