Kyle Banks

awsprof: Set Access and Secret Key Environment Variables by Profile Name

Written by @kylewbanks on Mar 11, 2017.

Named profiles are a great way to simplify working with multiple AWS accounts and profiles, but it can be a little tedious when it comes to using SDKs and third-party applications that don’t provide support for them.

For example, with the AWS CLI you can use the –profile flag to specify the credentials you want to use whenever issuing a command, for example:

$ aws s3 list-buckets --profile production

This will search the ~/.aws/credentials file for a profile named production and use the associated access/secret keys defined there when issuing the command. However, not all tools support profiles, so I wrote a quick little tool called awsprof to try and alleviate some of this pain.

awsprof supports two variations, listing and setting of profiles. Running the awsprof command with no arguments returns the name of all configured profiles, and if one of the profiles matches the current AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, it will be marked as the active profile with an asterisk:

$ awsprof
 * default

Running awsprof with a profile name allows you to activate the pair of AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables associated with that profile. Unfortunately, due to the nature of environment variables, and the fact that a child process cannot set environment variables for the parent, awsprof can only output the export commands which you can then run:

$ awsprof website

You can either copy and paste the command to run it yourself, or more efficiently:

$ eval $(awsprof website)

For frequent usage, add an alias to your ~/.bash_profile:

# ~/.bash_profile

alias awsprof-website="eval $(awsprof website)"

And run it like so:

$ awsprof-website

awsprof is far from perfect, especially because of the way the environment variables have to be evaluated, but it has saved me a lot of time so far when switching between various profiles. Check it out on GitHub and let me know what you think!

Let me know if this post was helpful on Twitter @kylewbanks or down below!