Skip to content

Instantly share code, notes, and snippets.

@tfentonz
Last active November 28, 2023 09:17
Show Gist options
  • Save tfentonz/726ad57e072443ae6de832df8a5b07ed to your computer and use it in GitHub Desktop.
Save tfentonz/726ad57e072443ae6de832df8a5b07ed to your computer and use it in GitHub Desktop.
Set environment variables to use MFA token with AWS CLI
#!/bin/bash
#
# https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/
#
# Usage: source ~/bin/awssessiontoken
# arn:aws:iam::12345689012:mfa/ExampleMFADevice
mfa_arn=$(aws iam list-mfa-devices --query 'MFADevices[].SerialNumber' --output text)
echo "MFA ARN: $mfa_arn"
echo -n "Enter MFA Code: "
read code
get_session_token=$(aws sts get-session-token --serial-number "$mfa_arn" --token-code "$code" --output json)
export AWS_ACCESS_KEY_ID=$(echo "$get_session_token" | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo "$get_session_token" | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo "$get_session_token" | jq -r '.Credentials.SessionToken')
unset mfa_arn
unset code
unset get_session_token
Copy link

ghost commented Oct 4, 2022

This is a really useful, easy script. I've made the following changes for my own use as I have multiple IAM user accounts and keys:

aws_profile=$1
mfa_arn=$2

get_session_token=$(aws sts get-session-token --profile $1 --serial-number $2 --token-code "$code" --output json)

I then use an alias in my ~/.bash_profile

alias aws-account-1='source ~/bin/awssessiontoken aws-account-1 arn:aws:iam::12345689012:mfa/ExampleMFADevice'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment