Skip to content

Instantly share code, notes, and snippets.

@Bharathkumarraju
Last active August 15, 2019 23:00
Show Gist options
  • Save Bharathkumarraju/edb7223baa44d6cd15e18ece26400753 to your computer and use it in GitHub Desktop.
Save Bharathkumarraju/edb7223baa44d6cd15e18ece26400753 to your computer and use it in GitHub Desktop.
Use MFA token to authenticate access to AWS resources through the AWS CLI
#!/bin/bash
set -o pipefail
usage() {
echo 'Usage:
source ./script.sh <IAM_USERNAME> <MFA_CODE> <ACCOUNT_ID> <PROFILE_NAME>
Requires:
* jq
* aws cli
* PROFILE_NAME is default when you do 'aws configure' at first
'
}
if [ "$#" -ne 4 ]; then
usage
else
IAM_USERNAME="$1"
MFA_CODE="$2"
ACCOUNT_ID="$3"
PROFILE="$4"
GET_CREDENTIALS=`aws sts get-session-token --output json \
--serial-number arn:aws:iam::"$ACCOUNT_ID":mfa/"$IAM_USERNAME" \
--token-code "$MFA_CODE" \
--duration-seconds 9000 \
--profile "$PROFILE"`
export AWS_ACCESS_KEY_ID=$(echo ${GET_CREDENTIALS} | jq -c -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo ${GET_CREDENTIALS} | jq -c -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo ${GET_CREDENTIALS} | jq -c -r .Credentials.SessionToken)
export AWS_DEFAULT_REGION=ap-southeast-1
export AWS_DEFAULT_OUTPUT=json
export AWS_PROFILE=$PROFILE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment