Amazon Elastic Compute Cloud (EC2) is one of the most widely used AWS services for hosting applications and workloads in the cloud.
While AWS Management Console provides a user-friendly interface, managing hundreds of EC2 instances manually becomes inefficient and error-prone. Python automation with Boto3 allows organizations to perform instance operations consistently, securely, and at scale.
Boto3 is the official AWS SDK for Python that enables developers and DevOps engineers to interact with AWS services through code. It provides APIs for launching, monitoring, stopping, rebooting, and terminating EC2 instances.
| AWS EC2 instances managing with Python Boto3 SDK |
What are we doing?
Have you ever logged into the AWS Console just to start, stop, or reboot EC2 instances and wondered if there was a faster way?
As DevOps Engineers, Cloud Administrators, and Automation Architects, we perform repetitive EC2 management tasks every day. Instead of manually navigating through the AWS Console, we can automate these operations using Python and the AWS SDK called Boto3.
In this article, we will learn how to manage AWS EC2 instances programmatically using Python and unlock the power of cloud automation.
What We'll Learn
In this post we will be exploring the AWS EC2 Instance related operations, and manage them in a reusable form. By the end of this article, you will be able to:
- Configure AWS credentials for Python automation
- Connect to AWS EC2 using Boto3
- List EC2 instances and retrieve instance details
- Start EC2 instances programmatically
- Stop EC2 instances programmatically
- Reboot EC2 instances using Python
- Handle exceptions and permissions securely
- Understand real-world DevOps automation use cases
- Optimize AWS costs using scheduled automation
- Build reusable cloud automation scripts
Why Use Python for EC2 Management?
1. Faster Operations
Execute actions on multiple EC2 instances within seconds instead of manually selecting instances through the console.
2. Reduce Human Errors
Automation ensures consistent execution and eliminates accidental operational mistakes.
3. Cost Optimization
Automatically stop development and testing servers during non-business hours and restart them when needed. This helps reduce unnecessary cloud spending.
4. Infrastructure Automation
Integrate EC2 management into GitLab CI/CD pipelines, operational workflows, and self-healing systems.
5. Better Scalability
Manage a few servers or thousands of instances using the same automation code.
Real-World DevOps Use Cases
Environment Scheduling
- Start Development servers at 8 AM
- Stop Development servers at 8 PM
- Reduce AWS operational costs
Maintenance Windows
- Reboot application servers automatically
- Apply patches during approved maintenance periods
Disaster Recovery
- Start standby servers during DR testing
- Validate infrastructure readiness
Auto-Healing
- Detect unhealthy instances
- Trigger automated restart or recovery actions
Cloud Governance
- Identify untagged instances
- Generate compliance reports
- Enforce operational standards
How do you Create EC2 instance using Python3 Boto3?
#=============================================
# File : create_ec2.py
# Description: Create EC2 instance by Boto3
import boto3
ec2 = boto3.resource('ec2')
instances = ec2.create_instances(
ImageId="ami-0dafa01c8100180f8",
MinCount=1,
MaxCount=1,
InstanceType="t2.micro",
KeyName="KeyPair1"
)
Launch instance
import boto3
ec2_client = boto3.client('ec2')
# This function will requires
# image_id [Required] based on the region this will be changing
# instance_type [optional] default t2.micro type otherwise you can provide
# max [optional] default as 1, you can provide maximum number of instances
def launch_instance(image_id, instance_type='t2.micro', max=1):
resource = ec2_client.run_instances(ImageId=image_id,
InstanceType=instance_type,
MinCount=1, MaxCount=max)
for instance in resource['Instances']:
print(instance['InstanceId'])
# main program
launch_instance('yourami-id')
To control the ec2 instances individual AWS cli commsnd test Start, Stop
ec2.start_instances
ec2.stop_instances
and terminate the ec2 instance
List AWS EC2 Instances using python boto3 script
import boto3
ec2_client = boto3.client('ec2')
resp = ec2_client.describe_instances()
for reservation in resp['Reservations']:
for instance in reservation['Instances']:
print("Running Instance Image ID: {} Running instance Instance Type: {} Running Instance Keyname {}".format(instance['InstanceId'],instance['InstanceType'],instance['KeyName']))
Python code with Menu driven program to manage EC2 instances
import boto3
import time
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
## Display all instances
def display_instances():
for instance in ec2.instances.all():
print (instance.id , instance.state)
## Stop instance by given instance id
def stopinstance():
instanceid=input("Please enter instanceid:")
response = ec2_client.stop_instances(InstanceIds=[instanceid])
time.sleep(90)
display_instances()
## Terminate instance by given instance id
def terminateinstance():
instanceid=input("Please enter instanceid:")
response = ec2_client.terminate_instances(InstanceIds=[instanceid])
time.sleep(90)
display_instances()
## Start instance by given instance id
def startinstance():
instanceid=input("Please enter instanceid:")
response = ec2_client.start_instances(InstanceIds=[instanceid])
time.sleep(90)
display_instances()
## Main Program
def main():
while True:
menu_list=["Display All Instance","Stop Instance","Start Instance","Terminate Instance","Exit"]
i=1
for item in menu_list:
print (i,item)
i=i+1
choice=int(input("Please enter Menu Choice:"))
if choice==1:
display_instances()
elif choice==2:
stopinstances()
elif choice==3:
startinstances()
elif choice==4:
terminateinstance()
else:
exit()
if __name__ == '__main__':
main()
Best Practices cloud Automations
1. Use IAM Roles Instead of Hardcoded Credentials
Avoid storing AWS Access Keys inside Python scripts.
Use:
- IAM Roles
- Instance Profiles
- AWS SSO
- Temporary Security Credentials
This improves security and aligns with AWS best practices.
2. Use DryRun Before Production Actions
Before stopping or rebooting instances, perform a DryRun operation to verify permissions and prevent accidental outages. AWS EC2 APIs support DryRun validation for many instance management actions.
3. Use Tags for Better Automation
Instead of hardcoding instance IDs:
Environment=Dev Application=WebApp Owner=DevOps
You can dynamically locate and manage resources using tags.
Major Benefits we can observe:
- Easier maintenance
- Better governance
- Simplified automation
Benefits of Boto3-Based EC2 Automation
| Benefit | Description |
|---|---|
| Faster Execution | Perform operations in seconds |
| Cost Savings | Automatically stop unused resources |
| Scalability | Manage hundreds of instances |
| Reliability | Consistent execution every time |
| Security | IAM-based access control |
| Integration | Works with Jenkins, GitLab, GitHub Actions |
| Monitoring | Collect operational information automatically |
| Compliance | Enforce cloud governance policies |
Reader Challenge
Try extending this script with the following features:
Beginner
- List only running EC2 instances
- Display instance Name tags
Intermediate
- Start or stop instances based on tags
- Generate CSV reports
Advanced
- Schedule automatic shutdowns
- Send notifications through SNS
- Create self-healing workflows
- Integrate with AWS Lambda and EventBridge
Conclusion
Python and Boto3 provide a powerful combination for automating AWS EC2 operations. Whether you are a DevOps Engineer, Cloud Administrator, Site Reliability Engineer, or Automation Architect, EC2 automation helps reduce manual effort, improve reliability, and optimize cloud costs.
By leveraging Boto3 APIs, you can build scalable automation solutions for monitoring, scheduling, maintenance, compliance, and disaster recovery operations. As cloud environments continue to grow, automation becomes an essential skill for every modern infrastructure engineer.
Reader Question
What is the most useful EC2 automation you have implemented in your organization?
Share your experience in the comments and help fellow cloud engineers learn from real-world use cases.
Comments
Post a Comment