If you are looking to provision the EC2 instance in AWS cloud then there are many ways of doing it and one of the best way to do by invoking a simple Python Script using Boto3.
In this tutorial we will create a AWS EC2 instance using Python.
Prerequisites
This post will be a step-by-step tutorial. If you’d like to follow along, ensure you have the following in place:
- An AWS account
- An IAM user with an access key ID and secret key set up on your local machine. You can find steps to set up IAM users Access key and Secret key from here.
Ensure the IAM user is set up for programmatic access and that you assign it to the existing policy of AmazonEC2FullAccess.
- Python v3.6 or later installed on your local machine. This tutorial will be using Python v3.11 on a Windows 10 machine.
Creating AWS EC2 instance using Python boto3 client
To create a Python script on your windows or Linux machine create a file named main.py and copy/paste the below code. The code below:
- Imports the boto3 library which is used to connect to AWS API’s.
- Next line of code creates a (ec2_client ) client. Boto3 supports two types of interactions with AWS; resource or client levels. The client level provides low-level service access while the resource level provides higher-level, more abstracted level access. This tutorial will use client access.
- Next we use client to run a instance (ec2_client.run_instances) and store the information in instances variable.
- Final line of code prints the instance id from the instance variable which is of type dictionary.
import boto3
def create_instance():
ec2_client = boto3.client("ec2", region_name="us-east-1")
instances = ec2_client.run_instances(
ImageId="ami-005f9685cb30f234b",
MinCount=1,
MaxCount=1,
InstanceType="t2.micro",
KeyName="demo_ec2"
)
print('The instance launched in ${region_name}' ["Instances"][0]["InstanceId"])
create_instance()
Executing Python boto3 Script to Launch AWS EC2
Now, we have created the code, lets run the Python with the below command.
python main.tf

Verifying the AWS EC2 in AWS Management console.

Conclusion
You should now have the basic knowledge to manage EC2 instances with the Boto3 EC2 Python SDK. Performing tasks in the Management Console such as creating, tagging, listing, and describing instances should be a thing of the past!