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

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