How to create an Ec2 instance using Python boto3?

+1 vote
I want to create an Ec2 instance using Python boto3?

Can anyone help me with the code?
Dec 3, 2018 in AWS by Nitesh
• 2,950 points

1 answer to this question.

0 votes

You can use the following code, it worked for me perfectly.

import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
    ImageId = 'ami-009d6802948d06e52',
    MinCount = 1,
    MaxCount = 1,
    InstanceType = 't2.micro',
    KeyName = 'nabarupa',
    SubnetId = 'subnet-0yhg678990d56c277')
print (instance[0].id)

Hope this helps.

answered Dec 3, 2018 by Nabarupa
What happens if I do not mention a subnetID?
If you don't specify a subnet-id then it will create a EC2 in the default VPC.
Thank you. That makes sense.
this command is getting error
What error are you getting @eroor?
botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation. Encoded authorization failure message: ALqMcu-fVPRmySsgfXHSJj5DAjtEbiZFBw8tgYLwxSIjxNxTtWMrzdzD5sxQu78cwg7iJFqj9CWk6h3KPFphfQCvnyoV0FbJb5dpqlN-IgyS5j1RF0tlb6svi87AqjXA_jGscpbYeI77AQnxOUR4VgqM6vjv47bkZyJ_MBWAwlGeewZJEnS-zYDtOVKBQKQn-woymsBRxFbcNg2oqwCBdO4DQEOvGmWv8K9PKby3lIJVtryeKA5kpoZBuxnz2DsXZ4eN8OQkP78azP2qjIvutYCoN2BnCKvpiqA5BeSC-ldOGUGyKj3afPA23PFraMDw8SDr0UFCdHQLBy167lw7zGtBuE97Q0RTavcTBLTwsRcuwdz0hqebx7XI5FuPxiGw14oPFMbgH0xMPXULnsn6i3x2O2iC8_i1XBgyc85W11L8iNN-1Hnnrdpwg5q8_w2UjgPvIqGmnE-6ayoJocCWYhi2_zggx3XY85GLsOQ0JUutCt9eHeik7UdAX3PYVVWyOiMWbk2FZNmxbiTfFsuqMdoR9bkOs8CX9CYh3u9NAX2G-v4QA5t04cBpAYT1EKpox1yHdbM_GBGLE04sZkWWK3r-mLGfSdRL1S4T9VoSrwU4vLif4kPy4P3kWHq5DVc517jAFLi_CjPDHRXNv_hfyZmBvsZIQg

i am getting this error
Check if you have all the required access. Your IAM user will require FullAccess to ec2 instances. Also allow programmatic access.

Related Questions In AWS

0 votes
1 answer

How to create an EC2 instance using Python?

Hey JunDevOps, Have a look these scripts: 1. ...READ MORE

answered Jun 24, 2019 in AWS by Aysha

edited Jun 25, 2019 1,348 views
0 votes
1 answer

How to Pass the VPC ID while creating the Ec2 instance in AWS using Python Boto3

import boto3 ec2 = boto3.resource('ec2') instance = ec2.create_instances( ...READ MORE

answered Jan 29, 2019 in AWS by Priyaj
• 57,510 points
+1 vote
1 answer
0 votes
1 answer

AWS S3 uploading hidden files by default

versioning is enabled in your bucket.….... the ...READ MORE

answered Oct 4, 2018 in AWS by Priyaj
• 57,510 points
0 votes
1 answer

How to decrypt the encrypted S3 file using aws-encryption-cli --decrypt

Use command : aws s3 presign s3://mybucket/abc_count.png you get ...READ MORE

answered Oct 22, 2018 in AWS by Priyaj
• 57,510 points
0 votes
1 answer

Import my AWS credentials using python script

Using AWS Cli  Configure your IAM user then ...READ MORE

answered Nov 16, 2018 in AWS by Jino
• 5,630 points
0 votes
2 answers
+1 vote
1 answer