Rotate AWS Access Keys via Script

05-04-2021

It’s a good idea to rotate your AWS Access Keys regularly, here is a simple script that makes the process easy and painless. For a lot of engineers it’s a compliance requirement to rotate keys on a regular cadence, it also takes a little effort and requires us to remember.

The idea behind the script is simple:

  1. Use current AWS Access Key to retrieve key(s) for current user, write them to a local file
  2. Request a new key
  3. Setup the new key on the local machine
  4. Delete the old access key
  5. Cleanup

To avoid having to remember to rotate regularly, or before I get the compliance naughty email I also have a cronjob configured to run weekly.

The script: (also available here)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/bash

# Inspired by: https://uly.me/aws-rotate-iam-keys/

# This script will automate the rotation of AWS access keys, which should be rotated regularly for security and compliance reasons

# TO USE:

# Update the following variables:
# - USER - Your AWS user name
# - LOCAL_BASE_PATH - The location of the .aws folder for your user. Will contain a config and credentials file

# Set some variables
USER=''
LOCAL_BASE_PATH=''

AWS="docker run --rm -it -v $LOCAL_BASE_PATH:/root/.aws amazon/aws-cli"

NEW_KEY_FILE="$LOCAL_BASE_PATH/new-access-key.json"
OLD_KEY_FILE="$LOCAL_BASE_PATH/old-access-key.json"
CREDENTIALS_FILE="$LOCAL_BASE_PATH/credentials"

# Retrieve Old credentials
echo 'LISTING EXISTING KEYS'
$AWS iam list-access-keys --user-name $USER > $OLD_KEY_FILE

# Create new key
echo 'CREATING NEW KEY'
$AWS iam create-access-key --user-name $USER > $NEW_KEY_FILE


# Backup old credentials
cp $CREDENTIALS_FILE $LOCAL_BASE_PATH/credentials-backup

# SET new access keys and new secret variables
NEW_ACCESS_KEY=$(grep -o '"AccessKeyId": "[^"]*' $NEW_KEY_FILE | grep -o '[^"]*$')
NEW_ACCESS_SECRET=$(grep -o '"SecretAccessKey": "[^"]*' $NEW_KEY_FILE | grep -o '[^"]*$')

# store the new key
echo '[default]' > $CREDENTIALS_FILE
echo 'aws_access_key_id = '$NEW_ACCESS_KEY >> $CREDENTIALS_FILE
echo 'aws_secret_access_key = '$NEW_ACCESS_SECRET >> $CREDENTIALS_FILE
sleep 10

# Delete old key
OLD_ACCESS_KEY=$(grep -o '"AccessKeyId": "[^"]*' $OLD_KEY_FILE | grep -o '[^"]*$')

echo 'DELETING KEYS'
$AWS iam delete-access-key --user-name $USER --access-key-id $OLD_ACCESS_KEY

# Cleanup
rm $NEW_KEY_FILE
rm $OLD_KEY_FILE

The base of this script was inspired by: https://uly.me/aws-rotate-iam-keys/