boto3:使用instanceprofile / IAM角色创建实例

时间:2016-10-31 18:57:25

标签: amazon-web-services boto3

我想写一个为我启动服务器的脚本并进行设置。它应该:

  • 创建两个S3-Buckets并设置其CORS(已解决)
  • 根据图片创建ec2服务器
  • 授予此服务器访问该存储桶的权限

到目前为止,我发现了如何创建存储桶以及如何创建实例本身:

#@see http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#ec2

aws = boto3.Session(profile_name="myProfile")

s3 = aws.resource('s3', region_name='my-region-1')
bucket = s3.create_bucket(
    Bucket='my-cool-bucket', 
    #...
)
#...

ec2 = aws.resource('ec2', region_name='my-region-1')

ec2.create_instances(
     ImageId="my-ami-image-id",
     MinCount=1,  # I want exactly 1 server
     MaxCount=1,
     KeyName='my-ssh-key',
     SecurityGroupIds=['my-security-group'],
     UserData=myStartupScript, # script that will start when server starts
     InstanceType='t2.nano',
     SubnetId="my-subnet-id",
     DisableApiTermination=True,
     PrivateIpAddress='10.0.0.1',
     #...
)

但是,我现在如何为该服务器创建角色并授予该角色对存储桶的访问权限?

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

您需要:

  • 创建InstanceProfile
  • 将角色与实例配置文件相关联
  • 使用IamInstanceProfile参数
  • 启动实例

答案 2 :(得分:0)

创建一个名为 Test-emr-instance-role 的角色,然后可以使用此代码创建实例配置文件并将角色附加到该实例配置文件。

session = boto3.session.Session(profile_name='myProfile') 
iam = session.client('iam')

instance_profile = iam.create_instance_profile (
    InstanceProfileName ='Test-emr-instance-profile' 
)

response = iam.add_role_to_instance_profile (
    InstanceProfileName = 'Test-emr-instance-profile',
    RoleName            = 'Test-emr-instance-role' 
)