By Dan Roncadin, Chief Consultant
I often need to work with multiple AWS accounts. There are personal accounts, business accounts, and various client accounts. This adds up to a lot of different credentials. I need a way of quickly and accurately switching between these various credential sets while making it clear to me which account I’m currently working with.
The CLI is a must for any serious work in AWS, but it doesn’t have a great way of managing multiple accounts or credentials. There is a profile system that can be set up in the ~/.aws/config file but that requires tacking –profile onto every command which is easily forgotten and leads to challenges scripting across multiple environments. Otherwise, the CLI relies on environment variables like AWS_ACCESS_KEY_ID being set.
Enter Direnv (http://direnv.net/). Direnv lets you specify a file (.envrc) which is executed in the local shell to load environment variables every time you enter a directory. Even better, once you leave the directory it unloads the environment variables so you don’t accidentally have them set and then execute a command against the last account you were working with.
I create a directory structure for each client and account that I work with. Then moving between accounts is as simple as changing directories:
Each of my directories has an .envrc file with the following:
I then go further and designate subdirectories for defaulting to different regions.
~/aws/personal/test-account-1/us-west-2 has this .envrc file: source_env .. export AWS_DEFAULT_REGION=us-west-2
The “source_env” line instructs direnv to use the variables included in the parent directory’s .envrc file rather than unloading them when loading the current directory’s file.
This should be enough to get you started, but read the docs at http://direnv.net to see the full usage capability and how to integrate with your favorite shell. It’s available on OS X, Linux, and for Windows in Cygwin.
As a bonus, if you’re concerned with securing the credentials, you can create that directory structure in an encrypted volume and then mount/unmounts is as necessary. At a minimum, at least set the permissions on .envrc files to 600.