skip to Main Content

I have an AWS config file that my boto3 session has access to, via the AWS_CONFIG_FILE environment variable.
The config file looks like this: (multi-account environment)

[profile profile1]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER 1>:role/all-profiles-same-role-name
[profile profile2]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER 2>:role/all-profiles-same-role-name
[profile profileN]
credential_source Environment
region=us-east-whatever
role_arn=arn:aws:iam:<ACCOUNT NUMBER N>:role/all-profiles-same-role-name

In my Python code, I am trying to setup RefreshableCredentails (boto3 method) using somethign like this: (excluding full code because I think the issue is mainly about parsing the aws_config_file):

def __get_session_credentials(self):
   # hardcode one role_arn for now but need to variablize
   session_ttl=3000
   aws_role_arn="arn:aws:iam::<ACCOUNT NUM>:role/all-profiles-same-role-name
   ...

Can I somehow parse the "role_arn" from the config file on a per profile basis to make that function more extensible? How would I do that?

2

Answers


  1. You can use the configparser module from the standard library:

    import configparser
    
    from pathlib import Path
    
    
    def main():
    
        path_to_config = Path(Path.home(), ".aws", "config")
        parser = configparser.ConfigParser()
        parser.read(path_to_config)
    
        for profile in parser.sections():
    
            if "role_arn" in parser[profile]:
                print(
                    "Found profile", profile, "with role_arn", parser[profile]["role_arn"]
                )
    
    
    if __name__ == "__main__":
        main()
    

    I’m not going to share the output here, though 😉

    Login or Signup to reply.
  2. I think that your problem could be solved if you configure a new environment variable AWS_PROFILE

    According to boto3 docs[1]:

    AWS_PROFILE

    The default profile to use, if any. If no value is specified, Boto3 attempts to search the shared credentials file and the config file for the default profile.

    And aws-cli (just for reference) docs[2]:

    AWS_PROFILE

    Specifies the name of the AWS CLI profile with the credentials and options to use. This can be the name of a profile stored in a credentials or config file, or the value default to use the default profile.

    If defined, this environment variable overrides the behavior of using the profile named [default] in the configuration file. You can override this environment variable by using the –profile command line parameter.


    So, just set this environment variable to the profileN

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search