Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Boto3 to launch an EC2 instance with an IAM role?

I can not figure out how to launch an EC2 instance in Boto3 with a specified IAM role.

Here is some sampe code of how I have been able to successfully create an instance so far:

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
ec2.create_instances(ImageId='ami-1e299d7e', InstanceType='t2.micro',\
MinCount=1, MaxCount=1, SecurityGroupIds=['Mysecuritygroup'], KeyName='mykeyname')
like image 778
Gerk Avatar asked Jan 07 '17 05:01

Gerk


People also ask

How can I launch an EC2 instance with an IAM role?

To attach an IAM role to an instanceOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, choose Instances. Select the instance, choose Actions, Security, Modify IAM role. Select the IAM role to attach to your instance, and choose Save.

Which permissions are required to launch EC2 instances with an IAM role?

If an IAM user wants to launch an EC2 instance, you need to grant the EC2 RunInstances permission to that user.


1 Answers

Note: Some Boto3 versions accept either Arn or Name but all versions accept Name. I suggest using the role name only.

IamInstanceProfile={
    'Arn': 'string',
    'Name': 'string'
}

If your profile name is ExampleInstanceProfile and the ARN is arn:aws:iam::123456789012:instance-profile/ExampleInstanceProfile

ec2.create_instances(ImageId='ami-1e299d7e',
                     InstanceType='t2.micro',
                     MinCount=1, MaxCount=1,
                     SecurityGroupIds=['Mysecuritygroup'],
                     KeyName='mykeyname',
                     IamInstanceProfile={
                            'Arn': 'arn:aws:iam::123456789012:instanceprofile/ExampleInstanceProfile'
                            'Name': 'ExampleInstanceProfile'
                     })
like image 191
helloV Avatar answered Oct 19 '22 13:10

helloV