How to use MFA with AWS CLI?

前端 未结 13 1184
太阳男子
太阳男子 2020-12-05 00:05

How do I type in the MFA code when using the AWS CLI? I have checked the documentation page of IAM http://docs.aws.amazon.com/cli/latest/reference/iam/index.html.

I

13条回答
  •  有刺的猬
    2020-12-05 00:48

    On Windows

    I'm on windows and I created a batch file to pass in my MFA code and have it automatically set up my credentials. First, you need to set up your production credentials in AWS:

    aws configure --profile prod
    

    Answer the questions appropriately with your key and secret. Then, I run my script like this:

    C:\> mfa-getCreds.bat 229168
    
    Your credentials are set up, and will expire on 2019-05-12T04:04:13Z
    
    Now you should be able to run aws commands like this: aws s3 ls
    

    Here are the contents of my mfa-getCreds.bat:

    @echo off
    
    set TOKEN=%1
    if not defined TOKEN goto showUsage   
    
    @call aws sts get-session-token --profile prod --serial-number "arn:aws:iam::109627855994:mfa/ryan.shillington" --token-code %* > c:\temp\mfa-getCreds.json
    
    FOR /F "tokens=* USEBACKQ" %%g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET AWS_ACCESS_KEY=%%g)
    FOR /F "tokens=*" %%g IN ('jq -r ".Credentials.SecretAccessKey" c:\temp\mfa-getCreds.json') do (SET "AWS_SECRET_KEY=%%g")
    FOR /F "tokens=*" %%g IN ('jq -r ".Credentials.SessionToken" c:\temp\mfa-getCreds.json') do (SET "AWS_SESSION_TOKEN=%%g")
    FOR /F "tokens=*" %%g IN ('jq -r ".Credentials.Expiration" c:\temp\mfa-getCreds.json') do (SET "EXPIRATION=%%g")
    
    set AWS_ACCESS_KEY_ID=%AWS_ACCESS_KEY%
    set "AWS_SECRET_ACCESS_KEY=%AWS_SECRET_KEY%"
    
    echo.
    echo Your credentials are set up, but will expire on %EXPIRATION%
    echo.
    echo Now you should be able to run aws commands like this: aws s3 ls
    
    goto :EOF
    
    :showUsage
    echo Usage: %0 [MFA Token]
    goto :EOF
    

    For this to run, you'll need the excellent jq package in your path.

提交回复
热议问题