> /dev/null

Interesting hacks, snippets, and shortcuts.

Apr 14

Keeping your AWS credentials safe on the command line

Sometimes you need run tasks locally that connect to AWS. If this is touching a real system, you don't want to leave the credentials sitting in clear text. Fortunately, Apple's keychain has a command line interface that lets you access securely stored passwords.

Here are some simple steps to put your AWS credentials in the environment only for commands that need them.

1. Create a Keychain entry for your secret key

Go into Keychain Access (/Applications/Utilities/Keychain Access.app) and add a new item.

Give it the name "AWS Secret Access Key", set the account name to "aws_secret_key", and set the password to your secret access key:

Adding the keychain entry

You can now access the key like so:

security find-generic-password -wa aws_secret_key

Which will prompt you with a dialog confirming that you want allow access:

Keychain access prompt dialog

I don't use the "Always Allow" option because having it prompt me every time makes it less likely that I will accidentally run a command from my bash history.

2. Create a wrapper script to load your credentials

Now that the password is stored, you need an easy way to retrieve it.

The following shell script will load your key into the AWS_SECRET_ACCESS_KEY environment variable; which is where all of the tools I use look for it.

It will also set your AWS_ACCESS_KEY_ID environment variable since they are generally needed together.

#! /bin/bash
export AWS_ACCESS_KEY_ID="<Your Access Key ID>"
export AWS_SECRET_ACCESS_KEY="$(security find-generic-password -wa aws_secret_key)"

I have this saved in my bin directory as with_aws_credentials and I can use it like so:

Wrapper in action

And upon clicking allow...

Credentials working