Stopping EC2’s with Python Boto3

A Beginner’s Guide to Creating a Python Boto3 Script to Stop EC2 Instances with Defined Parameters

Melissa (Mel) Foster
Women in Technology
7 min readMay 22, 2023

--

Edited Adobe Stock Free Image

If you have found this article, you might be in a similar situation and starting to push yourself to learn all you can surrounding Python Boto3. I’m glad you are here! Today, I will be providing you a walk-through on how to utilize Python Boto3 scripts to create EC2s and stop them within AWS Cloud9.

A little background //

Boto3 is an AWS SDK (software development kit) created to improve the use of Python. Boto3 is used to create, configure, and manage AWS services. One example of these services is, Amazon Elastic Compute Cloud (Amazon EC2) which we will be demonstrated further in this article. A neat little side note: the creator of the original Boto library, Mitch Garnaat, named it after the fresh water dolphin native to the Amazon river.

Foundational Objective //

  • Create a Python script you can run that will stop all instances.

To follow along with this project you will need //

  • Access to AWS
  • An Configured AWS Cloud9 with Boto3
  • An Optional GitHub Account
  • Attention to Details

To be able to stop running EC2s, you need to have running EC2s. If you currently do not know how to create one, feel free to refer back to this article for a quick refresh.

https://medium.com/@mel.foster/launching-an-aws-ec2-instance-creating-a-custom-webpage-75c5ebd3e1c5

For added fun, let’s try to create a few EC2s using the AMI off one of the existing EC2s that is already running.

Open up one of your running EC2s. Look for the AMI. Copy the number we will need it for our script.

With that info now in hand, go to your Cloud9 Environment. On a new branch we can build our Python Boto3 Script and save it. Then we will test it by running our script to see if we can successfully create a few EC2s for this project.

  • Open a New File from Template
  • Delete the default lines
  • Add import boto3
  • Save as Create_Instance_Quick.py

If you refer to the link below regarding AWS & Boto3, you can find all the ways to utilize ec2.client. You can also find create_instances options. I learned off a a really talented coach a great script to create instances. I just shortened it for a quick example for this project.

import boto3

ec2 = boto3.resource('ec2')

instance = ec2.create_instances(
ImageId = 'ami-0889a44b331db0194',
MinCount = 3,
MaxCount = 3,
InstanceType = 't2.micro',
)
print(instance)

If we head back over to our EC2 Dashboard, we can now see under Instances an additional three running EC2s.

Success so far!

With creation out of the way, let’s work on completing the assigned objective: creating a script to stop all instances. Before heading back to our Cloud9 Environment, if you open up the documentation on boto3 (linked below) you can see that there is a method for stopping instances: stop_instance, and the required parameters include InstanceIds.

Starting with a new Python file, save it as Stop_Instance.py. Let’s test a quick delete by running the script below with one of the IDs of the EC2 we created.

import boto3

ec2 = boto3.resource('ec2')

ec2.Instance('i-017e71753440509ce').stop()

Checking our EC2 Dashboard again, we can verify if the EC2 is in fact stopped.

I think it is great we were able to achieve this, but it’s not really going to be efficient is it? (Even if we add in all the specified EC2s. ) Especially with this scenario you might run into in the field:

A DevOps engineering team often uses a development lab to test releases of their application. Management is concerned about the rising costs of the development lab and would like to save money by stopping (for this example) three EC2 instances after all the engineers are clocked out. We want to ensure that only Development instances are stopped to make sure nothing in Production is accidentally stopped.

Let’s get organized and create a script to solve this scenario. Over on our EC2 Dashboard, we can view our Current Running EC2s.

From here we can select our Instance IDs, and adjust their names and tags. This will help us with defining our script.

Adjusting Name //

  • If you click on the little pencil, you can adjust the name of your EC2.
    I adjusted my last running to be Named Green Team Dev & Green Team Production.

Adjusting Tag //

  • Select EC2
  • Select Action
  • Then from the drop down menu select Instance Settings
  • From here, another drop down opens. Select Manage Tags.
  • Update Tags
  • Repeat steps for all Dev EC2s

With your EC2 Tags being Adjusted to Key: Environment and Value: Dev, we are ready to go back to Cloud9 and finish our script.

Note: We will be trying something different vs our first simplified Python Boto3 Script. We ran our first scripts utilizing .resource. Resource is a higher-level abstractions of AWS services compared to client, it allows for simpler code since you don’t have to worry with a lot of underlying detail. It has its benefits, but unfortunately it isn’t available for all AWS Resources; eventually you will need to be familiar with client.

  • Update ec2 resource line to client:
ec2 = boto3.client('ec2')
  • Begin with creating a filter to verify the running EC2’s:
    (You can once again refer to EC2 Boto3 Documentation and look for describe_instances.)
# Identify running instances with a specific tag
response = ec2.describe_instances(
Filters=[
{'Name': 'tag:Environment', 'Values': ['Dev']},
{'Name': 'instance-state-name', 'Values': ['running']}
]
)
  • You can adjust your script with hashtags ‘#’ to grey out the script we previously created. Using a hashtag you can also comment use of code.
  • We will need to add an empty list to store the information we just requested:
# Create an empty list to store instance IDs
instance_ids=[]
  • Extract the Instance IDs with the required reservation:
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])
  • Create the commands to stop the instances:
# Stop the instances with the obtained instance IDs
response = ec2.stop_instances(
InstanceIds=instance_ids
)
  • Add an optional success print message:
# Print a message indicating the development instances have been stopped
#successfully
print("You have successfully stopped Development Instances.")

Put all together our Stop_Instance.py script should now look like this:

import boto3

ec2 = boto3.client('ec2')

# To stop specific instance:
#ec2.Instance('i-017e71753440509ce').stop()

# Identify running instances with a specific tag
response = ec2.describe_instances(
Filters=[
{'Name': 'tag:Environment', 'Values': ['Dev']},
{'Name': 'instance-state-name', 'Values': ['running']}
]
)

# Create an empty list to store instance IDs
instance_ids=[]

# Extract instance IDs from the response
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_ids.append(instance['InstanceId'])

# Stop the instances with the obtained instance IDs
response = ec2.stop_instances(
InstanceIds=instance_ids
)

# Print a message indicating the development instances have been stopped
#successfully
print("You have successfully stopped Development Instances.")
  • Save and run the script
Woo-hoo!! Success!!

Let’s verify on our EC2 Dashboard

The key to success is attention to details. I incorrectly tagged an EC2 and made adjustments before my run. Make sure you are paying attention. An easy misspelling, or mislabeling can cause errors. I am glad that I reviewed by tags before executing. Saved myself a little headache for sure!

Thank you again for joining me with this project! I hope you learned a few more ways of successfully stopping an EC2. Remember, if you no longer need the EC2s you created, Terminate them from the EC2 Dashboard. Don’t forget to commit your successful scripts to your GitHub. Treat yourself to a relaxing break before you begin your next challenge, you deserve it!

Edited Adobe Stock Free Image

Helpful Resources //

Join me on https://www.linkedin.com/in/melissafoster08/ or follow me at https://github.com/mel-foster

--

--

Melissa (Mel) Foster
Women in Technology

𝔻𝕖𝕧𝕆𝕡𝕤 𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿 |𝒲𝑜𝓂𝑒𝓃 𝐼𝓃 𝒯𝑒𝒸𝒽 𝒜𝒹𝓋𝑜𝒸𝒶𝓉𝑒 | 𝚂𝚘𝚌𝚒𝚊𝚕 𝙼𝚎𝚍𝚒𝚊 𝙲𝚛𝚎𝚊𝚝𝚘𝚛 | Photographer