Working with botocore’s ~/.aws/config

This entry is part 2 of 6 in the series Boto

I ran into a bug in botocore and this post will serve to document a work around as well as show how to use botocore session object to work with the values stored in ~/.aws/config.

Pretend you have an aws config with two accounts for two separate projects, like so:


[profile project1]
account_id = 111111111111
# Optional, to define default region for this profile.

[profile project2]
account_id = 222222222222
# Optional, to define default region for this profile.

Now instead of using a single object, we create multiple objects, one for each profile we intend to use.

>>> import botocore.session
>>> session1 = botocore.session.get_session()
>>> session2 = botocore.session.get_session()
>>> session1.profile = 'project1'
>>> session2.profile = 'project2'
>>> session1.get_credentials().access_key
>>> session2.get_credentials().access_key

Also figured out how to get at the `account_id` integer:

>>> session1.get_scoped_config()['account_id']

Here is another algorithm that returns a list of sessions objects, one for each profile listed in the config.

>>> import botocore.session
>>> sessions = []
>>> aws_config = botocore.session.get_session().full_config
>>> for profile_name in aws_config['profiles']:
...     session = botocore.session.get_session()
...     session.profile = profile_name
...     sessions.append(session)

Series NavigationFiltering AWS resources with Boto3Setting region programmatically in Boto3

One thought on “Working with botocore’s ~/.aws/config

  1. session1.get_scoped_config()[‘account_id’] didn’t work for me. For session1.get_scoped_config(), i got
    {‘aws_access_key_id’: ‘THISISNOTMYACCESSKEY2’,
    ‘aws_secret_access_key’: ‘THISISNOTMYSECRETKEY2’,
    ‘region’: ‘us-west-2’}
    like this. There is not ‘account_id’ here. Correct me, if i am wrong.

    2. Also, could you let me know whether we can achieve the above task with boto3 module too

Leave a Reply

Your email address will not be published. Required fields are marked *