如何使用Boto3启动具有IAM角色的EC2实例?

20

我不知道如何在Boto3中使用指定的IAM角色启动EC2实例。

以下是我目前成功创建实例的一些示例代码:

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')
2个回答

20

注意:某些Boto3版本接受ArnName,但所有版本都接受Name。建议仅使用角色名称。

IamInstanceProfile={
    'Arn': 'string',
    'Name': 'string'
}
如果您的配置文件名称为ExampleInstanceProfile,ARN为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'
                     })

3
好的,谢谢!只是需要注意一下,它说: “参数 'iamInstanceProfile.name' 不能与 'iamInstanceProfile.arn' 结合使用。” - Gerk
以下是一些注释:
  1. 对于您想要附加的IAM角色,您还需要创建一个实例配置文件,并将其名称传递给上面的命令。如果您通过控制台创建了该角色,则会自动为您创建与角色名称相同的实例配置文件。
  2. 您需要为调用create_instances服务添加以下IAM权限以添加实例配置文件 - ec2.AssociateIamInstanceProfileiam.PassRole
- Utkarsh Dalal

8

补充一下helloV的优秀答案(由于信誉限制,我无法进行评论)。我遇到了相同的错误消息:“参数iamInstanceProfile.name不能与iamInstanceProfile.arn结合使用。因此只允许使用一个键。我尝试过两个参数,使用

IamInstanceProfile={ 'Name': 'ExampleInstanceProfile' }

对我来说可行,但不适用于

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

我正在使用boto3 1.4.4版本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接