aws-rotate-access-keys

nicolaw 24th June 2021 at 2:23pm
CodeSnippets
#!/usr/bin/env bash
# vim:ts=2:sw=2:tw=79

#
# Will rotate the credentials for the user and account that you have currently
# configured. It will print the shell `export` lines to use the credentials.
#
# If you use STS with MFA to access the API, you must use those STS credentials.
#

set -Eeuo pipefail
shopt -s extglob
shopt -s nocasematch
shopt -s extdebug

# Secure environment.
IFS=$' \t\n'
unset -f unalias
# shellcheck disable=SC1001
\unalias -a
unset -f command
if ! PATH="$(command -p getconf PATH 2>/dev/null)" && [[ -z "$PATH" ]]; then
  PATH="/usr/bin:/bin"
fi
PATH+=":/usr/local/bin" # Optionally necessary for Homebrew on Darwin.

# shellcheck disable=SC2154
trap 'declare rc=$?;
      >&2 echo "Unexpected error (exit-code $rc) executing $BASH_COMMAND at ${BASH_SOURCE[0]} line $LINENO";
      exit $rc' ERR

main () {
  declare username=""
  username="$(aws sts get-caller-identity \
    --query Arn \
    --output text \
    | cut -f 2 -d /)"

  declare old_access_keys=""
  old_access_keys="$(aws iam list-access-keys \
    --user-name "$username" \
    --query 'AccessKeyMetadata[].AccessKeyId' \
    --output text)"

  aws iam create-access-key \
    --query '[AccessKey.AccessKeyId,AccessKey.SecretAccessKey]' \
    --output text \
    | awk '{ print "export AWS_ACCESS_KEY_ID=\"" $1 "\"\n" "export AWS_SECRET_ACCESS_KEY=\"" $2 "\"" }'

  declare old_key=""
  for old_key in $old_access_keys
  do
    aws iam delete-access-key --access-key-id "$old_key" || true
  done
}

main "$@"