How to create an ec2 instance using boto3

60,670

Solution 1

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: http://boto3.readthedocs.org/en/latest/guide/migrationec2.html#launching-new-instances

Solution 2

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',
    ],
)

Solution 3

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.)

Solution 4

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

Solution 5

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)
Share:
60,670
MikA
Author by

MikA

Updated on January 14, 2020

Comments

  • MikA
    MikA over 4 years

    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.