AWS: Boto3: AssumeRole example which includes role usage

前端 未结 7 1412
梦毁少年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:00

    Assuming that 1) the ~/.aws/config or ~/.aws/credentials file is populated with each of the roles that you wish to assume and that 2) the default role has AssumeRole defined in its IAM policy for each of those roles, then you can simply (in psuedo-code) do the following and not have to fuss with STS:

    import boto3
    
    # get all of the roles from the AWS config/credentials file using a config file parser
    profiles = get_profiles()
    
    for profile in profiles:
    
        # this is only used to fetch the available regions
        initial_session = boto3.Session(profile_name=profile)
    
        # get the regions
        regions = boto3.Session.get_available_regions('ec2')
    
        # cycle through the regions, setting up session, resource and client objects
        for region in regions:
            boto3_session = boto3.Session(profile_name=profile, region_name=region)
            boto3_resource = boto3_session.resource(service_name='s3', region_name=region)
            boto3_client = boto3_sessoin.client(service_name='s3', region_name=region)
    
            [ do something interesting with your session/resource/client here ]
    
    
    • Credential Setup (boto3 - Shared Credentials File)
    • Assume Role Setup (AWS)

提交回复
热议问题