Skip to main content

Cloud

Enable/Disable Termination Protection in EC2 For 100 Instances

Glass Hourglass With Glowing Sand

Manually enable/disable for 100 Instances is a difficult task. To overcome this task we have some automated processes.

It’s possible to automate the process in one short using Python SDK.

List of Ec2 instances:

Python Code:

import boto3

 

def disable_termination_protection(instance_id):
    ec2 = boto3.client('ec2')
    response = ec2.modify_instance_attribute(
        InstanceId=instance_id,
        DisableApiTermination={
            'Value': False
        }
    )
    print(f"Termination protection disabled for instance {instance_id}")

 

# Get running instances
ec2 = boto3.client('ec2')
response = ec2.describe_instances(
    Filters=[
        {
            'Name': 'instance-state-name',
            'Values': ['running']
        }
    ]
)

 
# Disable termination protection for each running instance
for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        instance_id = instance['InstanceId']
        disable_termination_protection(instance_id)

The above code you will find the running instance and disable the instance termination.

After executing we can check this manually for any random 5 instances.

Happy learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Jeevanantham Balakrishnan

Jeevanantham Balakrishnan works at Perficient as Technical Consultant. He has a firm understanding of technologies like Databricks, Spark, AWS, and DevOps. He is keen to learn new technologies.

More from this Author

Categories
Follow Us