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

Ger*_*erk 13 python amazon-ec2 amazon-web-services amazon-iam boto3

我无法弄清楚如何在具有指定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')
Run Code Online (Sandbox Code Playgroud)

hel*_*loV 14

注意:有些Boto3版本接受要么 Arn Name,但所有版本的接受Name.我建议仅使用角色名称.

IamInstanceProfile={
    'Arn': 'string',
    'Name': 'string'
}
Run Code Online (Sandbox Code Playgroud)

如果您的个人资料名称是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'
                     })
Run Code Online (Sandbox Code Playgroud)

  • 那很有效,谢谢!只是注意,它说:`参数'iamInstanceProfile.name'可能不会与'iamInstanceProfile.arn'结合使用 (2认同)

Uyn*_*nix 6

只是helloV给出了一个很好的答案(由于声誉限制,我无法发表评论).我遇到了同样的错误消息"参数'iamInstanceProfile.name'可能不会与'iamInstanceProfile.arn'结合使用".所以只允许一个键.我试验了两者并使用了

IamInstanceProfile = {'Name':'ExampleInstanceProfile'}

适合我,但没有使用

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

我正在使用boto3版本1.4.4