How to use Boto3 to run an EC2 instance with the IAM role?

I cannot figure out how to start an EC2 instance in Boto3 with the specified IAM role.

Here is the sampe code, how I was able to successfully create the instance:

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') 
+12
source share
2 answers

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

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

If your profile name is ExampleInstanceProfile and 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' }) 
+13
source

Just an addition to the excellent answer from helloV (I can not comment due to reputation restrictions). I found the same error message: "The iamInstanceProfile.name parameter cannot be used in conjunction with iamInstanceProfile.arn . Therefore, only one key is allowed. I experimented with both and used

 IamInstanceProfile={ 'Name': 'ExampleInstanceProfile' } 

works for me but doesn't use

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

I am using Boto3 version 1.4.4

+5
source

Source: https://habr.com/ru/post/1013855/


All Articles