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

倾然丶 夕夏残阳落幕 提交于 2019-12-05 13:07:14

问题


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')

回答1:


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'
                     })



回答2:


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



来源:https://stackoverflow.com/questions/41518334/how-do-i-use-boto3-to-launch-an-ec2-instance-with-an-iam-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!