Last active
February 12, 2020 15:01
-
-
Save beezly/6d88a316064926e062835383de48610b to your computer and use it in GitHub Desktop.
My shonky script for rotating AWS CLI access credentials - requires jq
This file contains 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 -e | |
# First step, backup the old creds | |
tsec=$(date +%s) | |
pushd ~/.aws >/dev/null | |
tar -zcf "credential-backup-${tsec}.tar.gz" config credentials | |
popd > /dev/null | |
# Get the current key ID | |
current_key=$(aws configure get aws_access_key_id) | |
echo "Rotating access_key with id ${current_key}" | |
# Create a new key | |
new_key=$(aws iam create-access-key) | |
access_key_id=$(jq -r .AccessKey.AccessKeyId <<< $new_key) | |
secret_access_key=$(jq -r .AccessKey.SecretAccessKey <<< $new_key) | |
# Test the new key so that we know when it has started working (usually takes about 5 seconds) | |
working=10 | |
while [[ working -ne 0 ]]; do | |
AWS_ACCESS_KEY_ID=${access_key_id} AWS_SECRET_ACCESS_KEY=${secret_access_key} aws sts get-caller-identity >& /dev/null && break | |
working=$((working-1)) | |
if [[ working -eq 0 ]]; then | |
echo "New Access Credentials took too long to validate for Access Key ${access_key_id}" | |
exit 99 | |
fi | |
sleep 1 | |
done | |
# Ok - Configure the CLI. | |
aws configure set aws_access_key_id "${access_key_id}" | |
aws configure set aws_secret_access_key "${secret_access_key}" | |
aws iam delete-access-key --access-key-id "${current_key}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment