在 AWS 強制使用 MFA 的情況下,透過 CLI 操作

AWS 可以設定 IAM 使用者強制使用 MFA (包括 API 的操作),在這種情況下如果要使用 AWS Command Line Interface 就得透過 AWS STS (AWS Security Token Service) 產生另外一組 key + secret + session key,然後這組通行時間預設是 12 小時。

相關的文章可以參考「How do I use an MFA token to authenticate access to my AWS resources through the AWS CLI?」這篇,然後我就寫了一段 shell script 來做這件事情。

首先是在 ~/.aws/config 內放入 MFA 的 ARN,像是這樣:

[profile mycompany]
mfa = arn:aws:iam::012345678901:mfa/gslin
region = us-east-1

然後就可以用 aws.mfa mycompany 指令產生出一個會把 key + secret + session key 包進去的 shell:

function aws.mfa() {
    local MFA_ARN
    local MFA_TOKEN
    local PROFILE="$1"
    local STSDATA

    MFA_ARN="$(python3 -c "import configparser; import os; c=configparser.ConfigParser(); c.read('{}/.aws/config'.format(os.environ['HOME'])); print(c['profile ${PROFILE}']['mfa'])")
"
    echo "Reading ${PROFILE} and going for token ${MFA_ARN} ..."

    echo -n 'MFA Password: '
    read -r MFA_TOKEN

    STSDATA="$(aws --profile "${PROFILE}" sts get-session-token --serial-number "${MFA_ARN}" --token-code "${MFA_TOKEN}")"
    export AWS_ACCESS_KEY_ID="$(echo "${STSDATA}" | jq -r .Credentials.AccessKeyId)"
    export AWS_SECRET_ACCESS_KEY="$(echo "${STSDATA}" | jq -r .Credentials.SecretAccessKey)"
    export AWS_SESSION_TOKEN="$(echo "${STSDATA}" | jq -r .Credentials.SessionToken)"

    echo 'Running an independant shell...'
    ${SHELL}
}

很明顯的裡面用到了 Python 3 與 jq,這兩個應該都可以直接裝系統的版本就可以了。

後續的操作就跟原來的用法都一樣,像是 aws --region=us-east-1 s3 ls 這樣的指令。

2 thoughts on “在 AWS 強制使用 MFA 的情況下,透過 CLI 操作”

  1. 我看到的是 12 hours:

    You'll receive output with temporary credentials and an expiration time for those temporary credentials (by default, 12 hours) in a format similar as follows:

Leave a Reply

Your email address will not be published. Required fields are marked *