How to create an ec2 instance using boto3
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Amazon EC2 (Elastic Compute Cloud) lets you spin up virtual servers on demand. When you manage infrastructure at scale, clicking through the AWS console for each instance is not practical. Boto3, the official AWS SDK for Python, gives you a programmatic way to create, configure, and tear down EC2 instances in reproducible scripts.
This article walks you through launching an EC2 instance with Boto3 from scratch, including security group setup, tagging, waiting for the instance to be ready, and cleaning up when you are done.
Prerequisites
Before writing any code, make sure you have:
- An active AWS account with an IAM user that has the
AmazonEC2FullAccesspolicy (or equivalent permissions). - AWS credentials configured locally via
aws configureor environment variables (AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY). - Python 3.8+ and Boto3 installed (
pip install boto3). - A key pair already created in the AWS console (or via Boto3) so you can SSH into the instance.
- An AMI ID for your desired operating system (for example,
ami-0abcdef1234567890for Amazon Linux 2 in us-east-1).
Setting Up a Security Group
A security group acts as a virtual firewall. You should create one that allows only the traffic you need before launching an instance.
Restricting the CIDR to your specific IP address is a good security practice. Opening 0.0.0.0/0 for SSH is strongly discouraged in any environment beyond quick experiments.
Creating the EC2 Instance
The create_instances method on the EC2 resource is the central call. Here is a complete example with the most important parameters.
The TagSpecifications parameter lets you tag the instance at creation time, which is much cleaner than making a separate create_tags call afterward.
Waiting Until the Instance Is Running
create_instances returns immediately, but the instance needs time to boot. Use the built-in waiter to block until it reaches the running state.
Under the hood, wait_until_running polls the describe_instances API at regular intervals. If the instance fails to start within the default timeout (about 10 minutes), the waiter raises an exception.
Tagging After Launch
If you need to add or update tags after the instance is already running, use the create_tags method.
Tearing Down the Instance
When you are finished with the instance, terminate it and clean up the security group to avoid ongoing charges.
You must wait for the instance to fully terminate before deleting its security group, because AWS will not allow you to remove a security group that is still attached to a running or shutting-down instance.
Common Pitfalls
- Using the wrong AMI for the region. AMI IDs are region-specific. An AMI that works in us-east-1 will not exist in eu-west-1. Always look up the correct ID for your target region.
- Opening SSH to 0.0.0.0/0. This exposes port 22 to the entire internet. Restrict ingress rules to your own IP or a VPN range.
- Forgetting to specify
DeleteOnTerminationon EBS volumes. Without it, volumes persist after the instance is terminated and you keep paying for them. - Not waiting for state transitions. Calling
instance.public_ip_addressright aftercreate_instancesoften returnsNonebecause the IP has not been assigned yet. Always callwait_until_runningand thenreload. - Hardcoding credentials in source code. Never embed AWS keys in your Python files. Use environment variables, the
~/.aws/credentialsfile, or IAM roles attached to the machine running the script.
Summary
- Boto3 lets you automate EC2 lifecycle management entirely from Python, including creation, monitoring, and teardown.
- Always create a security group with the minimum necessary ingress rules before launching an instance.
- Use
TagSpecificationsincreate_instancesto tag resources at launch time rather than in a separate call. - Call
wait_until_runningandreloadbefore reading properties likepublic_ip_address. - Clean up instances and security groups when they are no longer needed to avoid unnecessary AWS charges.
Related reading
- How to create an Index in Amazon Redshift
- How to create AWS Glue table where partitions have different columns? 'HIVE_PARTITION_SCHEMA_MISMATCH
- How to Create Dataframe from AWS Athena using Boto3 get_query_results method
- How to create folder on S3 from Ec2 instance
- How to create conda environment with specific python version?
- How to create dict from class without None fields?
- How to create folder or key on s3 using AWS SDK for Node.js?
- How to create Kubernetes Namespace if it does not Exist?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.