Best method to renew periodically your AWS access keys

Viewed 21

I realized I never renewed muy AWS access keys, and they are credentials that should be renewed periodically in order to avoid attacks.

So... which is the best way to renew them automatically without any impact, if they are used just form my laptop?

1 Answers

Finally I created this bash script:

#!/bin/bash
set -e # exit on non-zero command
set -u # force vars to be declared
set -o pipefail # avoids errors in pipelines to be masked

echo "retrieving current account id..."
current_access_key_list=$(aws iam list-access-keys | jq -r '.AccessKeyMetadata')
number_of_current_access_keys=$(echo $current_access_key_list| jq length)
current_access_key=$(echo $current_access_key_list | jq -r '.[]|.AccessKeyId')

if [[ ! "$number_of_current_access_keys" == "1" ]]; then
  echo "ERROR: There already are more than 1 access key"
  exit 1
fi
echo "Current access key is ${current_access_key}"


echo "creating a new access key..."
new_access_key=$(aws iam create-access-key)
access_key=$(echo $new_access_key| jq -r '.AccessKey.AccessKeyId')
access_key_secret=$(echo $new_access_key| jq -r '.AccessKey.SecretAccessKey')
echo "New access key is: ${access_key}"

echo "performing credentials backup..."
cp ~/.aws/credentials ~/.aws/credentials.bak

echo "changing local credentials..."
aws configure set aws_access_key_id "${access_key}"
aws configure set aws_secret_access_key "${access_key_secret}"

echo "wait 10 seconds to ensure new access_key is set..."
sleep 10

echo "check new credentials work fine"
aws iam get-user | jq -r '.User'

echo "removing old access key $current_access_key"
aws iam delete-access-key --access-key-id $current_access_key

echo "Congrats. You are using the new credentials."
echo "Feel free to remove the backup file:"
echo "  rm ~/.aws/credentials.bak"

I placed that script into ~/.local/bin to ensure it is in the path, and then I added these lines at the end of my .bashrc and/or .zshrc files:

# rotate AWS keys if they are too old
if [[ -n "$(find ~/.aws -mtime +30 -name credentials)" ]]; then
  AWS_PROFILE=profile-1 rotate_aws_access_key
  AWS_PROFILE=profile-2 rotate_aws_access_key
fi

So any time I open a terminal (what is really frequently) it will check if the credentials file was not modified in more than one month and will try to renew my credentials automatically.

The worst thing that might happen is that it could create the new access key and not update my script, what should force me to remove it by hand.

Related