Reputation: 5542
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.
Upvotes: 38
Views: 76323
Reputation: 402
import boto3
ec2 = boto3.client('ec2', region_name='')
conn = ec2.run_instances(ImageId='<ami-image-id>',
InstanceType='<instance-type>',
MinCount=1,
MaxCount=5
)
Upvotes: 0
Reputation: 1325
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:
Upvotes: 43
Reputation: 56
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)
Upvotes: 2
Reputation: 4425
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',
],
)
Upvotes: 21
Reputation: 4821
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.)
Upvotes: 12
Reputation: 1843
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
Upvotes: 6