簡體   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