DEV Community

Mohammed N Zubair
Mohammed N Zubair

Posted on

Launching an EC2 Instance with Boto3 in Python

In this example, we'll use the AWS SDK for Python (Boto3) to programmatically launch an EC2 instance. This script demonstrates how to create a session with your AWS credentials and then use that session to start an EC2 instance in your specified region.

Key Steps:

Session Creation: We begin by creating a session with our AWS credentials.
EC2 Client: Using this session, we establish an EC2 client to interact with the EC2 service.
Launching an Instance: We then launch an EC2 instance by specifying the AMI ID, instance type, key pair, security group, and subnet.

import boto3

# Create a session using your credentials
session = boto3.Session(
    aws_access_key_id='access key need to paste', #replace wit your access key
    aws_secret_access_key='sec access key need to paste', #replace with your sec access key
    region_name='ap-southeast-1' # Replace with your region name
)

# Create an EC2 client
ec2_client = session.client('ec2')

# Launch an EC2 instance
response = ec2_client.run_instances(
    ImageId='ami-0a6b545f62129c495',  # Replace with your AMI ID
    InstanceType='t2.micro',          # Replace with your instance type
    MinCount=1,
    MaxCount=1,
    KeyName='sinapore-mac',      # Replace with your key pair name
    SecurityGroupIds=['sg-064b056b2a7650e76'],  # Replace with your security group ID
    SubnetId='subnet-08237211566f4e5f5'  # Replace with your subnet ID
)

# Print the instance ID
instance_id = response['Instances'][0]['InstanceId']
print(f'Launched instance with ID: {instance_id}')
Enter fullscreen mode Exit fullscreen mode

Top comments (0)