繁体   English   中英

boto3:创建具有 instanceprofile/IAM 角色的实例

[英]boto3: Create a instance with an instanceprofile/ IAM Role

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

  • 创建两个 S3-Bucket 并设置其 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',
     #...
)

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

我找到了创建 InstanceProfile 的方法:

https://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.ServiceResource.create_instance_profile

instance_profile = iam.create_instance_profile(
    InstanceProfileName='string',
    Path='string'
)

您将需要:

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

创建一个名为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' 
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM