How to create an ec2 instance using boto3

Question:

Is it possible to create an ec2 instance using boto3 in python?
Boto3 document is not helping here, and I couldn’t find any helping documents online. please provide some sample codes/links.

Asked By: MikA

||

Answers:

The API has changed but it’s right there in the documentation

# Boto 3
ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)

Link to the documentation:

Answered By: gbs

Refer to API docs has all available options to create instance

http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Subnet.create_instances

Answered By: ranjeetcao

The link you’re really looking for in the documentation is the create_instances() method of the ServiceResource object. This is the type of object you are calling if you create an EC2 resource like this:

s = boto3.Session(region_name="us-west-1")
ec2 = s.resource('ec2')
...
instance = ec2.create_instances(**y_kwargs)

This contains a more detailed example and a longer list of available parameters.

You can also get parameter values for AWS instances that are already running using the AWS command line interface:

$ aws ec2 describe-instances

This prints out a JSON file from which relevant parameters can be extracted and passed to the create_instances() method. (Or, you can use a boto client and call the describe_instances() method.)

(Note: If you’re wondering what the difference is between the Client and the Resource, they serve different purposes for the same end – the client is a lower-level interface while the Resource is a higher-level interface.)

Answered By: charlesreid1

You can run the code I used from the boto3 docs. You can add or remove parameters as per your requirements, but this is what you would normally require:

import boto3

client = boto3.client('ec2', region_name='us-west-2')

response = client.run_instances(
    BlockDeviceMappings=[
        {
            'DeviceName': '/dev/xvda',
            'Ebs': {

                'DeleteOnTermination': True,
                'VolumeSize': 8,
                'VolumeType': 'gp2'
            },
        },
    ],
    ImageId='ami-6cd6f714',
    InstanceType='t3.micro',
    MaxCount=1,
    MinCount=1,
    Monitoring={
        'Enabled': False
    },
    SecurityGroupIds=[
        'sg-1f39854x',
    ],
)
Answered By: captainblack

If your running from your windows computer you need configure AWS Cli with proper EC2 permisssion to launch instance.

#

import boto3

ec2 = boto3.resource('ec2')

instance = ec2.create_instances(
    ImageId='ami-5eb63a32',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro',
)
print(instance[0].id)
Answered By: Sonoo Kumar