AWS: Boto3: AssumeRole example which includes role usage

前端 未结 7 1396
梦毁少年i
梦毁少年i 2020-12-14 18:28

I\'m trying to use the AssumeRole in such a way that i\'m traversing multiple accounts and retrieving assets for those accounts. I\'ve made it to this point:



        
7条回答
  •  粉色の甜心
    2020-12-14 19:05

    Here's a code snippet from the official AWS documentation where an s3 resource is created for listing all s3 buckets. boto3 resources or clients for other services can be built in a similar fashion.

    # create an STS client object that represents a live connection to the 
    # STS service
    sts_client = boto3.client('sts')
    
    # Call the assume_role method of the STSConnection object and pass the role
    # ARN and a role session name.
    assumed_role_object=sts_client.assume_role(
        RoleArn="arn:aws:iam::account-of-role-to-assume:role/name-of-role",
        RoleSessionName="AssumeRoleSession1"
    )
    
    # From the response that contains the assumed role, get the temporary 
    # credentials that can be used to make subsequent API calls
    credentials=assumed_role_object['Credentials']
    
    # Use the temporary credentials that AssumeRole returns to make a 
    # connection to Amazon S3  
    s3_resource=boto3.resource(
        's3',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    
    # Use the Amazon S3 resource object that is now configured with the 
    # credentials to access your S3 buckets. 
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
    

提交回复
热议问题