Skip to content

Instantly share code, notes, and snippets.

@mrballcb
Created July 30, 2021 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrballcb/19c1b0ba01dd37208b55721e793d78aa to your computer and use it in GitHub Desktop.
Save mrballcb/19c1b0ba01dd37208b55721e793d78aa to your computer and use it in GitHub Desktop.
Save a copy of all users with access keys in an S3 bucket
#!/usr/bin/env bash
set -eu -o pipefail
MYROLE=elevated # Set to whatever you named your role
MYBUCKET=history # Set to whatever S3 bucket you will put this
DATE=$(date +%F)
AWS_ACCOUNT=$(aws sts get-caller-identity | jq -r .Account)
OUTPUT=$(aws sts assume-role \
--role-arn "arn:aws:iam::${AWS_ACCOUNT}:role/${MYROLE}" \
--role-session-name maint-${DATE}
export AWS_ACCESS_KEY_ID=$(echo $OUTPUT | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $OUTPUT | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $OUTPUT | jq -r '.Credentials.SessionToken')
S3_BUCKET=s3://$(aws s3 ls | grep $MYBUCKET | head -n 1 | awk '{print $3}')
tmpfile=$(mktemp)
USERLIST=$(aws iam list-users | jq -r .Users[].Username)
echo "AccessKeyMetaData:" > $tmpfile
for U in $USERLIST; do
KEYS=$(aws iam list-access-keys --user-name $U --output yaml | \
grep -v AccessKeyMetaData || \
true)
if [ "$KEYS" ]; then
echo -e "\n$KEYS"
fi
done
if echo $@ | grep -q -- "--test"; then
cat $tmpfile
else
aws s3 cp $tmpfile $S3_BUCKET/access-key-history/${DATE}_access-keys.txt
fi
rm $tmpfile
# vim: set bg=dark expandtab tw=72 sw=2 ts=2 sts=2 :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment