AWS: Boto3: AssumeRole example which includes role usage

前端 未结 7 1421
梦毁少年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 18:58

    After a few days of searching, this is the simplest solution I have found. explained here but does not have a usage example.

    import boto3
    
    
    for profile in boto3.Session().available_profiles:
    
        boto3.DEFAULT_SESSION = boto3.session.Session(profile_name=profile)
    
        s3 = boto3.resource('s3')
    
        for bucket in s3.buckets.all():
            print(bucket)
    

    This will switch the default role you will be using. To not make the profile the default, just do not assign it to boto3.DEFAULT_SESSION. but instead, do the following.

    testing_profile = boto3.session.Session(profile_name='mainTesting')
    s3 = testing_profile.resource('s3')
    
    for bucket in s3.buckets.all():
        print(bucket)
    

    Important to note that the .aws credentials need to be set in a specific way.

    [default]
    aws_access_key_id = default_access_id
    aws_secret_access_key = default_access_key
    
    [main]
    aws_access_key_id = main_profile_access_id
    aws_secret_access_key = main_profile_access_key
    
    [mainTesting]
    source_profile = main
    role_arn = Testing role arn
    mfa_serial = mfa_arn_for_main_role
    
    [mainProduction]
    source_profile = main
    role_arn = Production role arn
    mfa_serial = mfa_arn_for_main_role
    

    I don't know why but the mfa_serial key has to be on the roles for this to work instead of the source account which would make more sense.

提交回复
热议问题