Skip to content

Instantly share code, notes, and snippets.

@jvacek
Last active July 28, 2022 11:15
Show Gist options
  • Save jvacek/92f890c9fda11f951e2456f968cd2f75 to your computer and use it in GitHub Desktop.
Save jvacek/92f890c9fda11f951e2456f968cd2f75 to your computer and use it in GitHub Desktop.
`aws-cli` easy 2FA authentication

This will help you set up two functions to manage your login status when using two-factor authentication with the aws-cli tool.

Of course, the auth tokens only live within the terminal session's environment, and are not persistent.

You will need to start a new terminal session after following the instructions.

Usage

When done, you can perform any aws tasks without authenticating, like below.

aws-login 123456
aws s3 sync s3://bucket/file .
# Install requirements
## ubuntu/debian
apt install jq
# macos
brew install jq
# Download helper script
curl https://gist.githubusercontent.com/mankins/505f2834bae53276bc2d9b39b5c51ffd/raw/1d9439a621771c1e756e7aadfddc9d2e1df34454/aws-mfa.sh -o ./aws-mfa
chmod +x ./aws-mfa
# This should install the script into your $PATH
sudo mv ./aws-mfa /usr/local/bin
# Ensure serials are available
aws sts get-session-token --generate-cli-skeleton > ~/.aws/generate_token_nonprod.json
# Set the duration to 43200, and your MFA serial (e.g. arn:aws:iam::077777776969:mfa/[email protected])
## The serial should contain `mfa`, not `user`!
nano ~/.aws/generate_token_nonprod.json
# Add wrapper functions to your shell's profile
## Switch for ~/.bashrc, etc. if necessary
cat >> ~/.zshrc << 'EOF'
aws-clear(){
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
}
aws-login(){
aws-clear
TOKENS=$(aws-mfa $1)
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< ${TOKENS}
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment