Last active
October 16, 2019 08:43
-
-
Save indradhanush/f60f41e07c1f0d33086b81046c2155e4 to your computer and use it in GitHub Desktop.
AWS Access Key rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# This script rotates your aws access keys by creating | |
# a new one and deleting the older one. | |
# Requirements | |
# You must have a working aws cli configured already | |
# Run `aws configure` otherwise first before running this script. | |
# Installation & Usage | |
# Download the file | |
# Run `chmod +x rotate-aws-iam-keys.sh` | |
# Run `./rotate-aws-iam-keys` | |
# Limitations | |
# There is a max limit of 2 key pairs on AWS. | |
# As a result, this script will not work if you already | |
# have 2 access key pairs created. Because the script first | |
# creates a new key pair, and then deletes the older one | |
set -e | |
echo "Fetching current access keys in use..." | |
CURRENT_ACCESS_KEYS=$(aws iam list-access-keys) | |
CURRENT_ACCESS_KEY_ID=$(echo "$CURRENT_ACCESS_KEYS" | jq ".AccessKeyMetadata[0].AccessKeyId" | tr -d '"') | |
echo "Current access key id: $CURRENT_ACCESS_KEY_ID" | |
NEW_ACCESS_KEYS=$(aws iam create-access-key) | |
AWS_ACCESS_KEY_ID=$(echo "$NEW_ACCESS_KEYS" | jq ".AccessKey.AccessKeyId" | tr -d '"') | |
AWS_SECRET_ACCESS_KEY=$(echo "$NEW_ACCESS_KEYS" | jq ".AccessKey.SecretAccessKey" | tr -d '"') | |
echo "Configuring aws cli with access key $AWS_ACCESS_KEY_ID and secret access key $AWS_SECRET_ACCESS_KEY" | |
aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID | |
aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY | |
# Wait for the new keys to propagate to AWS | |
sleep 5 | |
echo "Deleting access key $CURRENT_ACCESS_KEY_ID..." | |
aws iam delete-access-key --access-key-id $CURRENT_ACCESS_KEY_ID |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment