AWS EC2 Management with Python and Boto3
In the world of cloud computing, Amazon Web Services (AWS) stands as a giant, with EC2 (Elastic Compute Cloud) being one of its most popular services. As developers and DevOps engineers, we often need to programmatically manage EC2 instances. Enter boto3, the AWS SDK for Python, which makes this task a breeze. In this blog post, we’ll explore how to use boto3 to launch and terminate EC2 instances.
Prerequisites
Before we dive in, make sure you have:
- Python installed on your machine
- AWS account with appropriate permissions
- AWS CLI configured with your credentials
- Boto3 installed (
pip install boto3
)
Setting Up
First, let’s import boto3 and create an EC2 client:
import boto3
ec2 = boto3.client('ec2')
Launching an EC2 Instance
To launch an EC2 instance, we’ll use the run_instances
method. Here's a basic script:
def launch_ec2_instance():
response = ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0', # Amazon Linux 2 AMI ID
InstanceType='t2.micro',
MinCount=1,
MaxCount=1,
KeyName='your-key-pair-name',
SecurityGroupIds=['sg-xxxxxxxxxxxxxxxxx'],
SubnetId='subnet-xxxxxxxxxxxxxxxxx',
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': 'Boto3-Instance'
},
]
},
]
)
instance_id = response['Instances'][0]['InstanceId']
print(f"Launched EC2 instance: {instance_id}")
return instance_id
# Call the function
new_instance_id = launch_ec2_instance()
This script does the following:
- Specifies the AMI ID, instance type, and other configuration details
- Launches a single instance (MinCount and MaxCount both set to 1)
- Assigns a tag with the name “Boto3-Instance”
- Returns and prints the new instance ID
Terminating an EC2 Instance
Terminating an instance is even simpler. Here’s how you can do it:
def terminate_ec2_instance(instance_id):
response = ec2.terminate_instances(
InstanceIds=[instance_id]
)
print(f"Terminating EC2 instance: {instance_id}")
return response
# Call the function
terminate_ec2_instance(new_instance_id)
This function takes an instance ID as an argument and terminates that instance.
Putting It All Together
Here’s a complete script that launches an instance, waits for it to be running, and then terminates it:
import boto3
import time
ec2 = boto3.client('ec2')
def launch_ec2_instance():
response = ec2.run_instances(
ImageId='ami-0c55b159cbfafe1f0',
InstanceType='t2.micro',
MinCount=1,
MaxCount=1,
KeyName='your-key-pair-name',
SecurityGroupIds=['sg-xxxxxxxxxxxxxxxxx'],
SubnetId='subnet-xxxxxxxxxxxxxxxxx',
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': 'Boto3-Instance'
},
]
},
]
)
instance_id = response['Instances'][0]['InstanceId']
print(f"Launched EC2 instance: {instance_id}")
return instance_id
def wait_for_running_state(instance_id):
waiter = ec2.get_waiter('instance_running')
print(f"Waiting for instance {instance_id} to reach 'running' state...")
waiter.wait(InstanceIds=[instance_id])
print(f"Instance {instance_id} is now running")
def terminate_ec2_instance(instance_id):
response = ec2.terminate_instances(
InstanceIds=[instance_id]
)
print(f"Terminating EC2 instance: {instance_id}")
return response
# Main execution
if __name__ == "__main__":
# Launch instance
new_instance_id = launch_ec2_instance()
# Wait for instance to be running
wait_for_running_state(new_instance_id)
# Keep instance running for a while
print("Instance will run for 5 minutes before termination...")
time.sleep(300)
# Terminate instance
terminate_ec2_instance(new_instance_id)
This script:
- Launches an EC2 instance
- Waits for the instance to reach the ‘running’ state
- Keeps the instance running for 5 minutes
- Terminates the instance
Best Practices and Considerations
- Error Handling: Add try-except blocks to handle potential AWS API errors.
- Credentials Management: Use AWS IAM roles when possible, especially on EC2 instances.
- Cost Management: Be cautious when launching instances to avoid unexpected costs.
- Security: Always use secure methods to handle sensitive information like access keys.
Conclusion
Boto3 provides a powerful and flexible way to manage AWS resources programmatically. By mastering these basic operations, you can automate complex workflows involving EC2 instances, making your AWS management tasks more efficient and less error-prone/
As you become more comfortable with boto3, you can explore more advanced features like managing multiple instances, working with other AWS services, or integrating EC2 management into larger applications or DevOps pipelines.
Remember, with great power comes great responsibility. Always double-check your scripts and use them cautiously, especially when dealing with production environments.
So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.
Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”
Connect me on Social Media: https://linktr.ee/mdshamsfiroz
Happy coding! Happy learning!
Happy coding!