Launching AWS EC2 Instance using Python

The need for engineers skilled in cloud services like Amazon Web Services (AWS) has increased as more companies around the world move their operations to the cloud. One of the most well-known services offered by AWS, EC2 (Elastic Compute Cloud), offers scalable computing capability. Python is frequently used to manage AWS resources, including launching EC2 instances, due to its vast ecosystem and ease of use. This article will show you how to use Python to launch an AWS EC2 instance with practical examples.

Understanding AWS EC2 and Python Boto3

AWS EC2 provides resizable computational capacity in the cloud. It is designed to simplify web-scale cloud computing by reducing the friction required for customers to acquire and configure capacity.

We use the Boto3 library, the Python Software Development Kit (SDK) for Amazon Web Services (AWS), to interact with AWS services. It enables Python developers to create applications that utilize services like Amazon S3, Amazon EC2, and others.

Setting Up Your AWS and Boto3

You must have an AWS account and have your AWS credentials configured on your computer before you can begin. You can set up credentials by installing the AWS CLI (Command Line Interface) and running aws configure.

The Boto3 module must be installed in your Python environment. Use pip to accomplish this ?

pip install boto3

After installation, you can import Boto3 to communicate with AWS services in your Python programs.

Launching AWS EC2 Instance: Step by Step Guide

Now, let's guide you through launching an EC2 instance using Python and Boto3.

Step 1: Import Boto3 Module

Your Python script should import the boto3 package ?

import boto3

Step 2: Create a Session

Create a Boto3 session with your AWS credentials ?

session = boto3.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='us-west-2'
)

Replace 'YOUR_ACCESS_KEY' and 'YOUR_SECRET_KEY' with your actual AWS access key and secret access key. You can choose the region according to your preferences.

Step 3: Create EC2 Resource Object

Create an EC2 resource object using the session object ?

ec2_resource = session.resource('ec2')

Step 4: Launch EC2 Instance

Launch the EC2 instance using the create_instances() method ?

instances = ec2_resource.create_instances(
    ImageId='ami-0c55b159cbfafe1f0',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro'
)

print(f"Launched instance: {instances[0].id}")

In the create_instances() function: ImageId is the AMI ID, MinCount and MaxCount are the minimum and maximum number of instances to launch, and InstanceType is the type of instance.

Complete Examples

Example 1: Launching a Single EC2 Instance

Here's a complete example that launches one EC2 instance ?

import boto3

# Create session with AWS credentials
session = boto3.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='us-west-2'
)

# Create EC2 resource
ec2_resource = session.resource('ec2')

# Launch instance
instances = ec2_resource.create_instances(
    ImageId='ami-0c55b159cbfafe1f0',  # Amazon Linux 2 AMI
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro'
)

print(f"Successfully launched instance: {instances[0].id}")
print(f"Instance state: {instances[0].state['Name']}")

Example 2: Launching Multiple EC2 Instances

To launch multiple instances, simply modify the MaxCount parameter ?

import boto3

session = boto3.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='us-west-2'
)

ec2_resource = session.resource('ec2')

# Launch 3 instances
instances = ec2_resource.create_instances(
    ImageId='ami-0c55b159cbfafe1f0',
    MinCount=1,
    MaxCount=3,
    InstanceType='t2.micro'
)

print(f"Launched {len(instances)} instances:")
for instance in instances:
    print(f"Instance ID: {instance.id}")

Example 3: Adding Tags to EC2 Instances

You can also apply tags to your instances at launch time for better organization ?

import boto3

session = boto3.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='us-west-2'
)

ec2_resource = session.resource('ec2')

instances = ec2_resource.create_instances(
    ImageId='ami-0c55b159cbfafe1f0',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro',
    TagSpecifications=[
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'MyPythonInstance'
                },
                {
                    'Key': 'Environment',
                    'Value': 'Development'
                }
            ]
        }
    ]
)

print(f"Launched tagged instance: {instances[0].id}")

Key Parameters

Parameter Description Required
ImageId AMI ID to use for the instance Yes
MinCount Minimum number of instances to launch Yes
MaxCount Maximum number of instances to launch Yes
InstanceType Type of instance (t2.micro, t3.small, etc.) Yes
KeyName Name of key pair for SSH access No
SecurityGroupIds Security group IDs for the instance No

Best Practices

  • Use IAM roles instead of hardcoding access keys in your code

  • Always tag your instances for better resource management

  • Specify security groups to control network access

  • Terminate instances when they're no longer needed to avoid charges

Conclusion

Using Python and Boto3 to launch AWS EC2 instances is straightforward and powerful. Remember to manage your instances effectively and always terminate them when finished to avoid unexpected charges. These examples provide a foundation that can be extended for more complex configurations like adding storage, security groups, or different instance types based on your requirements.

Updated on: 2026-03-27T08:04:41+05:30

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements