简体   繁体   中英

List resource for child account from master account using boto3?

I am using python and boto3 to list resource that my organization has. I am listing the resources from my master account without a problem but I also need to list the resource from the child accounts as well. I can get the child account ID's but that's pretty much it.

Any help?

You will need access to a set of credentials that belong to the child account.

From Accessing and Administering the Member Accounts in Your Organization - AWS Organizations :

When you create a member account using the AWS Organizations console, AWS Organizations automatically creates an IAM role in the account. This role has full administrative permissions in the member account. The role is also configured to grant that access to the organization's master account.

To use this role to access the member account, you must sign in as a user from the master account that has permissions to assume the role.

So, you can assume the IAM Role in the child account , which then provides a set of temporary credentials that can be used with boto3 to make API calls to the child account.

import boto3

role_info = {
    'RoleArn': 'arn:aws:iam::<AWS_ACCOUNT_NUMBER>:role/<AWS_ROLE_NAME>',
    'RoleSessionName': '<SOME_SESSION_NAME>'
}

client = boto3.client('sts')
credentials = client.assume_role(**role_info)

session = boto3.session.Session(
    aws_access_key_id=credentials['Credentials']['AccessKeyId'],
    aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
    aws_session_token=credentials['Credentials']['SessionToken']
)

An easier way is to put the role in your .aws/config file as a new profile. Then, you can specify a profile when making function calls:

# In ~/.aws/credentials:
[master]
aws_access_key_id=foo
aws_secret_access_key=bar

# In ~/.aws/config
[profile child1]
role_arn=arn:aws:iam:...
source_profile=master

Use it like this:

session = boto3.session.Session(profile_name='dev')
s3 = session.client('s3')

See: How to choose an AWS profile when using boto3 to connect to CloudFront

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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