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



我不知道如何使用指定的 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

最新更新