Skip to content

Instantly share code, notes, and snippets.

@drAlberT
Last active December 18, 2019 14:06
Show Gist options
  • Save drAlberT/5977d3225920287b00188f8b9927d68c to your computer and use it in GitHub Desktop.
Save drAlberT/5977d3225920287b00188f8b9927d68c to your computer and use it in GitHub Desktop.

Revisions

  1. drAlberT revised this gist Dec 18, 2019. 1 changed file with 12 additions and 3 deletions.
    15 changes: 12 additions & 3 deletions aws_iam_auth_mfa.sh
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,20 @@
    #!/usr/bin/env bash
    USER=${1}
    PROFILE=${AWS_PROFILE:-2}

    USER=${1?specify the user}
    PROFILE=${AWS_PROFILE:-$2}
    ACCOUNT_ID=${ACCOUNT_ID:-$3}

    set -ue -o pipefail

    echo -n "Enter MFA code for arn:aws:iam::${ACCOUNT_ID}:mfa/${USER}: "
    read MFA_CODE
    CREDENTIALS=$(aws sts get-session-token --serial-number "arn:aws:iam::${ACCOUNT_ID}:mfa/${USER}" --token-code "${MFA_CODE}" --profile "${PROFILE}" --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]" --output text)
    CREDENTIALS=$(aws sts get-session-token \
    --serial-number "arn:aws:iam::${ACCOUNT_ID}:mfa/${USER}" \
    --token-code "${MFA_CODE}" \
    --profile "${PROFILE}" \
    --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]" \
    --output text
    )
    IFS=$'\t' read -r -a CREDENTIALS_ARRAY <<< "${CREDENTIALS}"

    ACCESS_KEY_ID=${CREDENTIALS_ARRAY[0]}
  2. drAlberT created this gist Dec 18, 2019.
    20 changes: 20 additions & 0 deletions aws_iam_auth_mfa.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    #!/usr/bin/env bash
    USER=${1}
    PROFILE=${AWS_PROFILE:-2}
    ACCOUNT_ID=${ACCOUNT_ID:-$3}

    echo -n "Enter MFA code for arn:aws:iam::${ACCOUNT_ID}:mfa/${USER}: "
    read MFA_CODE
    CREDENTIALS=$(aws sts get-session-token --serial-number "arn:aws:iam::${ACCOUNT_ID}:mfa/${USER}" --token-code "${MFA_CODE}" --profile "${PROFILE}" --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]" --output text)
    IFS=$'\t' read -r -a CREDENTIALS_ARRAY <<< "${CREDENTIALS}"

    ACCESS_KEY_ID=${CREDENTIALS_ARRAY[0]}
    SECRET_ACCESS_KEY=${CREDENTIALS_ARRAY[1]}
    SESSION_TOKEN=${CREDENTIALS_ARRAY[2]}

    aws configure set aws_access_key_id "${ACCESS_KEY_ID}" --profile "${PROFILE}-mfa"
    aws configure set aws_secret_access_key "${SECRET_ACCESS_KEY}" --profile "${PROFILE}-mfa"
    aws configure set aws_session_token "${SESSION_TOKEN}" --profile "${PROFILE}-mfa"
    aws configure set region "eu-west-1" --profile "${PROFILE}-mfa"

    echo "MFA Credential set! Use them with --profile ${PROFILE}-mfa"