20

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')
helloV
  • 50,176
  • 7
  • 137
  • 145
Gerk
  • 303
  • 1
  • 2
  • 5

2 Answers2

20

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'
                     })
helloV
  • 50,176
  • 7
  • 137
  • 145
  • 3
    That worked, thank you! Just a note though, it says: `The parameter 'iamInstanceProfile.name' may not be used in combination with 'iamInstanceProfile.arn'` – Gerk Jan 07 '17 at 06:58
  • A few comments here: 1. For the IAM role you want to attach, you will also need to create an [instance profile](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html), whose name you will pass in to the command above. If you have created the role through the console, an instance profile will automatically be created for you with the same name as the role. 2. You will need to give the service calling `create_instances` the following iam permissions to add an instance profile - `ec2.AssociateIamInstanceProfile` and `iam.PassRole`. – Utkarsh Dalal Dec 08 '22 at 07:36
8

Just an addition to the great answer by helloV (I can not comment due to reputation limitations). I encountered the same error message of "The parameter iamInstanceProfile.name may not be used in combination with iamInstanceProfile.arn. So only one key is allowed. I experimented with both and using

IamInstanceProfile={ 'Name': 'ExampleInstanceProfile' }

works for me, but not using

IamInstanceProfile={'Arn':'arn:aws:iam::123456789012:instanceprofile/ExampleInstanceProfile'}

I am using boto3 version 1.4.4

NFR
  • 316
  • 2
  • 11
Uynix
  • 101
  • 1
  • 6