Skip to content

Instantly share code, notes, and snippets.

@jecolasurdo
Last active June 18, 2021 18:17
Show Gist options
  • Save jecolasurdo/1fc2d75233b7979d3d4c8d37f5abbeec to your computer and use it in GitHub Desktop.
Save jecolasurdo/1fc2d75233b7979d3d4c8d37f5abbeec to your computer and use it in GitHub Desktop.
Rotate your aws access keys.

Utility for rotating those pesky AWS access keys

Important: Only supports the default profile! If you have more than one profile setup via aws configure, this script is only capable of targetting the default profile. Other profiles are ignored.

To install and run:

  1. Copy the contents of install-and-run.sh to your terminal and press enter.
  2. Bash will download, install, and start the script.
  3. The script will prompt you for your AWS username (i.e. "Joe")
  4. Enter your username, and the script will create a new access key in AWS, add the access key to your local credentials file, and deactivate your old key.

After the script has been installed and run for the first time you can run it again at any time with the following steps:

  1. In a terminal, cd to the rotate-access-keys directory
  2. Activate the virtual environment a la . .virtualenv/bin/activate
  3. Run python3 rotate-access-keys.py
#! /bin/bash
mkdir rotate-access-keys && \
cd rotate-access-keys && \
wget https://gist.githubusercontent.com/jecolasurdo/1fc2d75233b7979d3d4c8d37f5abbeec/raw/rotate-access-keys.py && \
python3 -m venv .virtualenv && \
. .virtualenv/bin/activate && \
pip install boto3 && \
python3 rotate-access-keys.py
import fileinput
import os
import sys
from pprint import pprint
import boto3
def mask_key(key):
return "****************" + key[-4:]
USERNAME = input("Enter your AWS username: ")
AWS_CREDENTIALS_FILE = os.path.expanduser('~') + '/.aws/credentials'
iam = boto3.client('iam')
session = boto3.Session()
print("Retrieving current session credentials...")
current_credentials = session.get_credentials()
session_key_id = current_credentials.access_key
session_secret = current_credentials.secret_key
print("Gathering a list of current IAM keys...")
list_access_keys_response = iam.list_access_keys(UserName=USERNAME)
access_keys = list_access_keys_response['AccessKeyMetadata']
if len(access_keys) > 1:
print("Cleaning up old keys to make room for a new key...")
for access_key in access_keys:
key_id = access_key['AccessKeyId']
if key_id != session_key_id:
if access_key['Status'] == "Active":
print(" Deactivating key ({})...".format(mask_key(key_id)))
iam.update_access_key(
UserName=USERNAME, AccessKeyId=key_id, Status='Inactive')
print(" Deleting inactive key ({})...".format(mask_key(key_id)))
iam.delete_access_key(UserName=USERNAME, AccessKeyId=key_id)
print("Creating new key...")
create_access_key_response = iam.create_access_key(UserName=USERNAME)
new_key_id = create_access_key_response['AccessKey']['AccessKeyId']
new_secret = create_access_key_response['AccessKey']['SecretAccessKey']
print("New key ({}) created.".format(mask_key(new_key_id)))
print("Writing new key/secret to local credentials file...")
with open(AWS_CREDENTIALS_FILE, 'r') as file:
filedata = file.read()
filedata = filedata.replace(session_key_id, new_key_id)
filedata = filedata.replace(session_secret, new_secret)
with open(AWS_CREDENTIALS_FILE, 'w') as file:
file.write(filedata)
print("Deactivating old key ({})...".format(mask_key(session_key_id)))
iam.update_access_key(
UserName=USERNAME, AccessKeyId=session_key_id, Status='Inactive')
print("Testing new key ({})...".format(mask_key(new_key_id)))
iam_test = boto3.client('iam')
try:
iam.list_access_keys(UserName=USERNAME)
print("Test passed.")
print("Your key has been successfully rotated.")
except:
print("An error occured while updating your keys. Please update your keys manually via the AWS console.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment