Closing Time with Python

1_VKk4DP6SpO0oSXLVELv9cA.png

Using Python with boto3 to clean up your EC2 instances!

For this project I built a “set” of Python scripts that allow a user to create an number of EC2 instances with tags, then delete all instances with a certain tag (and excluding my Cloud9 instance). It’s a great little “end of the day” script to clean up extra instances and keep costs down.

Before we destroy, we must create!

Seeing as this project, and the development thereof, requires instances to terminate, let’s make a quick script to spin up n EC2 instances:

                import boto3

tags = []

def create_apache_ec2(client,tags):
    try:
        client.run_instances(MaxCount=1,
                         MinCount=1,
                         ImageId="ami-02d1e544b84bf7502",
                         InstanceType="t2.micro",
                         TagSpecifications=tags,
                         #KeyName="private-ec2",
                         #SecurityGroups=["launch-wizard-6"],
                         #UserData=boot_apache2_script,
                         )
        print("Started")
    except:
        print("Failed")
    


client = boto3.client('ec2')

#creating tags for instances
def tag_spec(user_key, user_value):
    global tags
    tags = [
            {
            "ResourceType":"instance",
            "Tags": [
                    {
                        "Key": user_key,
                        "Value": user_value
                    }
                ]
        }
    ]


#UNCOMMENT FOR USERDATA SCRIPT
#boot_apache2_script='''#!/bin/bash
#apt update -y
#apt upgrade -y
#apt-get install -y apache2
#systemctl start apache2
#systemctl enable apache2'''


def main():
    num_to_create = int(input("How many EC2 instances do you want to create: "))
    user_key = input("Please enter a tag for the instance. Key: ")
    user_value = input("Value: ")
    tag_spec(user_key,user_value)
    
    
    for i in range(num_to_create):
        create_apache_ec2(client,tags)
    


if __name__=="__main__":
    main()
            

As you can see, boto3 really does all the hard lifting for us. Simply import it, then create a client with the AWS service you need, and you’re off to the races!

Now for the fun part!

we all know this bad boy is the reason you’re here ;)

                #!/usr/bin/env python3.7

# --------------------------------------------------------------
# Program: Closing Time
# Programmer: Steven Laszloffy
# Project: LUIT Week 16
# Purpose: A simple program that shuts down all EC2 instances
# - protects the cloud9 instance
# - only stops "running" instances that have the Environment: Dev tag
# ---------------------------------------------------------------

import boto3

ec2 = boto3.client("ec2")

response = ec2.describe_instances()

reservations = response["Reservations"]

tagKey = "Environment"
tagVal = "Dev"



#function to get the list of instances that have the right tag        
def list_ec2_by_tag(tagKey, tagVal):
    response = ec2.describe_instances(
        Filters=[ #using filters instead of loops and if/else to find the needed instances
            {
                'Name': 'tag:'+tagKey,
                'Values': [tagVal]
            }
        ]
    )
    ec2List = []
    for reservation in (response["Reservations"]):
        for instance in reservation["Instances"]:
            #as a backup. Tag filter should render my cloud9 instance safe. But just in case...
            if ("i-03c38a1757c4f0702" != instance["InstanceId"]):
                print("Has tag: ",instance["InstanceId"])
                ec2List.append(instance["InstanceId"])
            
    return ec2List
    
#function to terminate the correct instances
def ec2_nuke(tgt_list):
    print("DELETING")
    #///NUKE\\\        
    ec2.terminate_instances(InstanceIds=tgt_list)
    


def main():
    ec2_nuke(list_ec2_by_tag(tagKey,tagVal))


if __name__=="__main__":
    main()
            

You may remember my comment from earlier regarding protecting my Cloud9 instance? Well, it turns out when you write a script to terminate instances… it’s super easy to nuke your own working environment! I’m not ashamed to admit this happened more than once! Finally, however, I got my logic right, and my Cloud9 environment was safe at last!

Conclude the shenanigans!

This one was pretty short and straightforward, so thank you for reading, and please feel free to check out this, and my other Python adventures on my GitHub!


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Avatar

Steven Laszloffy

Help Desk Manager, Bay de Noc Community College

@vypr907
Just a Halo nerd trying to transition from Tech Support to DevOps/Cybersecurity. I dabble with building apps.
Stats
16

Influence

249

Total Hits

1

Posts