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

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

我不知道如何使用指定的 IAM 角色在 Boto3 中启动 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')

注意:一些Boto3版本接受或者 Arn 或者 Name 但所有版本都接受 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'
                     })

只是对 helloV 的精彩回答的补充(由于声誉限制,我无法发表评论)。我遇到了相同的错误消息“参数 iamInstanceProfile.name 可能无法与 iamInstanceProfile.arn 结合使用。所以只允许使用一个键。我尝试了两个并使用

IamInstanceProfile={ 'Name': 'ExampleInstanceProfile' }

适合我,但不使用

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

我正在使用 boto3 版本 1.4.4