DEV Community

Revathi Joshi for AWS Community Builders

Posted on • Edited on • Originally published at Medium

How to stop Three specific EC2 Instances with Python script using boto3

Image description

Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python. It supports all current AWS cloud services, including Elastic Compute Cloud (EC2), DynamoDB, AWS Config, Cloud Watch, and Simple Storage Service. It allows you to directly create, update, and delete AWS resources from your Python scripts.

In this article, I am going to show you how to stop three EC2 instances with DEV tag using Python script with boto3.

Objectives:

  • Our DevOps engineering team often uses a development lab to test releases of our application.

  • The Managers are complaining about the rising cost of our development lab and need to save money by stopping our (for this example) 3 EC2 instances after all engineers are clocked out.

  • We want to ensure that only our Development instances are stopped to make sure nothing in Production is accidentally stopped.

  • Add logic to our python script that stops only running instances that have the Environment: Dev tag.

Note:

Added a logic not to stop our Cloud9 EC2 instance

Pre-requisites:

  • AWS user account with admin access, not a root account.
  • Cloud9 IDE comes with Python and boto3 installed.

Resources Used:

learn-to-code.workshop.aws
Boto3 documentation — Boto3 Docs 1.24.56 documentation

Let’s get started!

Create a new directory called — boto3_multiple_ec2 on the cloud9 environment.

mkdir <directory name>
cd boto3_multiple_ec2

I was very careful in working with small chunks of code when working with this script, to print out the ONLY three EC2 instances with the “DEV” tag, and not to knock off the EC2 instance of my Cloud9 environment.

Once Python script is working, I copy and pasted the code into a script — boto3_multiple_ec2.py

Here is the gist of the python script.

# --- boto3_python_projects/boto3_multiple_ec2.py ---

# AWS Python SDK
import boto3


# A low-level client representing Amazon Elastic Compute Cloud (EC2)
ec2_client=boto3.client("ec2")


# use Amazon service ec2
ec2_resource=boto3.resource("ec2")


# create 4 ec2 instances
ec2_resource.create_instances(
    ImageId='ami-090fa75af13c156b4',
    InstanceType='t2.micro',
    MaxCount=5,
    MinCount=5)


# List of ec2 instance ids
ec2_instance_ids = []


# iterate and prints all ec2 instances 
# EXCEPT Cloud9 id - i-0e6238103c9b3f9a8
response=ec2_client.describe_instances()


# reservations = response['Reservations']
for reservation in response['Reservations']:

    for instance in reservation['Instances']:
        # instanceId = instance["InstanceId"]
        # not to print Cloud9 id - i-0e6238103c9b3f9a8
        if ("i-0e6238103c9b3f9a8" != instance["InstanceId"]):
                print(instance["InstanceId"])
                ec2_instance_ids.append(instance["InstanceId"])


# create tags for 3 ec2 instances
# with **Environment: Dev** tag
response=ec2_client.create_tags(
    Resources=[
        ec2_instance_ids[1], ec2_instance_ids[2], ec2_instance_ids[3],
    ],
    Tags=[
        {
            'Key': 'Environment',
            'Value': 'dev',
        },
    ],
)


# filters **running** instances that have the **Environment: Dev** tag.
instances = ec2_resource.instances.filter(
    Filters = [{'Name': 'instance-state-name', 'Values': ['running']},
        {'Name': 'tag:Environment', 'Values':['dev']}])


# only stops **running** instances that have the **Environment: Dev** tag.
for instance in instances:
    try:
        instance.stop()
        print(f'{instance} stopped')
    except:
        print(f'Error stopping {instance}')
Enter fullscreen mode Exit fullscreen mode

You can also see the same code in my GitHub repository

What we have done so far

Created a python script with boto3 to stop three specific EC2 instances with “DEV” tags and to keep my Cloud9 EC2 instance alive!!!

Though it seems like a simple and straightforward script, I encountered many errors just to get the logic working. I like python and is fun to do projects with it.

Top comments (0)