How to stop Three specific EC2 Instances with Python script using boto3
Tags: python, boto3, aws, devops
Published: 2022-10-06 02:29:08


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjsqihn6lhj59y0ggfq6.png)


**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](https://catalog.us-east-1.prod.workshops.aws/workshops/3d705026-9edc-40e8-b353-bdabb116c89c/en-US)
[Boto3 documentation — Boto3 Docs 1.24.56 documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html)

_**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}')
```

You can also see the same code in my [GitHub repository](https://github.com/awsmine/boto3_python_projects/blob/main/boto3_multiple_ec2.py)

## 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.