Python script to launch AWS instance

Arpit Bisane
1 min readJan 24, 2023

Here is a Python script that uses the boto3 library to launch an AWS EC2 instance:

import boto3

# Replace with your own AWS access key and secret key
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"

# Create an EC2 client
ec2 = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-west-2')

# Specify the instance details
instance = ec2.run_instances(
ImageId='ami-0d5d9d301c853a04a', # Amazon Linux 2 AMI
InstanceType='t2.micro',
MinCount=1,
MaxCount=1,
KeyName='my_key', # Replace with your own key pair name
SecurityGroupIds=['sg-0d5d9d301c853a04a'] # Replace with your own security group ID
)

# Print the instance ID
print("Instance ID:", instance['Instances'][0]['InstanceId'])

In this script, you will need to replace “YOUR_ACCESS_KEY” and “YOUR_SECRET_KEY” with your own AWS access key and secret key. The script uses the boto3 library to create an EC2 client, and then uses the run_instances method to launch a new EC2 instance. The script specifies the instance details such as the Amazon Machine Image (AMI) ID, instance type, key pair name and the security group id of the instances.

It’s important to note that running this script will incur charges in your AWS account, so please make sure to terminate or stop the instances after using them to avoid unnecessary charges.

Please also make sure that the user that you are using to run this script has the permission to launch EC2 instances and appropriate roles assigned to it.

--

--