1

I have my .aws/credentials set as

[default]
aws_access_key_id = [key]
aws_secret_access_key = [secret! Shh!]

and .aws/config

[profile elevated]
role_arn = [elevated role arn]
source_profile = default
mfa_serial = [my device arn]

With the credentials and config files set up like that, boto3 will

automatically make the corresponding AssumeRole calls to AWS STS on your behalf. It will handle in memory caching as well as refreshing credentials as needed

so that when I use something like


session = boto3.Session(profile_name = "elevated")

in a longer function, all I have to do is input my MFA code immediately after hitting "enter" and everything runs and credentials are managed independent of my input. This is great. I like that when I need to assume a role in another AWS account, boto3 handles all of the calls to sts and all I have to do is babysit.

What about when I don't want to assume another role? If I want to do things directly as my user as a member of the group to which my user is assigned? Is there a way to let boto3 automatically handle the credentials aspect of that?

I see that I can hard-code into a fx my aws_access_key_id and ..._secret_... , but is there a way to force boto3 into handling the session tokens by just using the config and credentials files?

Method 2 in this answer looked promising but it also seems to rely on using the AWS CLI to input and store the keys/session token prior to running a Python script and still requires hard-coding variables into a CLI.

Is there a way to make this automatic by using the config and credentials files that doesn't require having to manually input AWS access keys and handle session tokens?

Steven
  • 3,238
  • 21
  • 50
  • You can get a session using the `default` profile by not specifying anything (`session = boto3.Session(profile_name = "elevated")`) - is there a reason why that would not work? – Daniel Scott Jan 10 '20 at 13:01

1 Answers1

0

If you are running the application on EC2, you can attach roles via EC2 Roles. On your code, you may dynamically get the credentials depending on which role you attach.

session = boto3.
credentials = session.get_credentials().get_frozen_credentials()

access_key = credentials.access_key
secret_key = credentials.secret_key
token = credentials.token

you may also want to use botocore.credentials.RefreshableCredentials to refresh your token once in a while

Ron Marcelino
  • 463
  • 3
  • 8
  • This only works if the application is on EC2? What if it's just running on my local machine? – Steven Nov 20 '19 at 13:51