To launch an Amazon Elastic Compute Cloud (EC2) instance using Python, you can use the boto3 library, which is the Amazon Web Services (AWS) SDK for Python.

This example assumes that you have already set up your AWS credentials and have the necessary permissions to launch an EC2 instance.

Install boto3 using pip

pip3 install boto3

Here’s an example of how you can use boto3 to launch an EC2 instance:

import boto3
# Create an EC2 client
ec2 = boto3.client('ec2')
# Choose an Amazon Machine Image (AMI) for the instance
ami_id = 'ami-01234567890abcdef'
# Choose a instance type for the instance
instance_type = 't2.micro'
# Specify the details of the security group for the instance
security_group_ids = ['security-group-id']
subnet_id = ['subnet-id']
# Storage details
BlockDeviceMappings = [
   {
     'DeviceName': '/dev/sda1',
     'Ebs': {
             'DeleteOnTermination': True,
             'VolumeSize': '20',
             'VolumeType': 'gp2'
           }
   },
]
# Availability Zone details
placement = {
    'AvailabilityZone': 'ap-south-1'
}
# UserData script
user_data = '''
    # update system
    sudo apt update
    '''
# Tags details
TagSpecifications = [
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'python-test-instance'
                }
            ]
        },
        {
            'ResourceType': 'volume',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'python-test-vol'
                }
            ]
        }
    ]
# Launch the instance
response = ec2.run_instances(
    ImageId=ami_id,
    InstanceType=instance_type,
    MinCount=1,
    MaxCount=1,
    SecurityGroupIds=security_group_ids,
    SubnetID=subnet_id,
    UserData=user_data,
    Placement=placement,
    BlockDeviceMappings=blockDevice_mappings,
    TagSpecifications=tag_specifications,
    DryRun=False
)
# Get the instance ID of the newly launched instance
instance_id = response['Instances'][0]['InstanceId']
print(f'Successfully launched EC2 instance with ID: {instance_id}')

For more information on launching EC2 instances using boto3, you can refer to the run_instances() and create_tags() documentation.

Hope this helps:)

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments