[LINUX] (Command conversion) MFA authentication in AWS CLI

Overview

If you have MFA configured for your IAM user to access the AWS Management Console MFA authentication is required when using the AWS CLI with the same user, I'll forget it soon, so I made it a command.

Rough setup procedure

  1. Create an access key (if you haven't done so yet)
  2. Add the following to .bashrc
  3. Log in again or source ~ / .bashrc

.bashrc




function AWSCLIINIT() {
    unset AWS_ACCESS_KEY_ID
    unset AWS_SECRET_ACCESS_KEY
    unset AWS_SESSION_TOKEN
    aws configure

    mfa_arn=`aws sts get-caller-identity --query 'Arn' --output text 2>/dev/null | sed -e "s/:user\//:mfa\//g"`
    if [ -n "$mfa_arn" ]
    then
        echo "YourMFA :"$mfa_arn
        echo -n INPUT YourMFA-Code :
        read mfa_code

        get_session_token=`aws sts get-session-token --output text --serial-number $mfa_arn --token-code $mfa_code 2>/dev/null`

        if [ -n "$get_session_token" ]
        then
            set -- $get_session_token
            export AWS_ACCESS_KEY_ID=$2
            export AWS_SECRET_ACCESS_KEY=$4
            export AWS_SESSION_TOKEN=$5
        else
            echo "MFA ERROR"
        fi

    else
        echo "aws configure is wrong"
    fi
}

How to use

AWSCLIINIT

--I'm doing ʻaws configure` inside, so enter it as needed --You will be asked for mfa, so enter it

$ AWSCLIINIT 
AWS Access Key ID [********************]: 
AWS Secret Access Key [********************]: 
Default region name [ap-northeast-1]: 
Default output format [json]: 
YourMFA :arn:aws:iam::123456789012:mfa/abcdefg
INPUT YourMFA-Code :123456
$

If there is no error, authentication is successful. Token etc. are set in the environment variable.

Like this.

Before MFA certification


$ aws iam get-user

An error occurred (AccessDenied) when calling the GetUser operation: User: arn:aws:iam::123456789012:user/abcdefg is not authorized to perform: iam:GetUser on resource: user abcdefg with an explicit deny

When using this command


$ aws iam get-user
{
    "User": {
        "UserName": "abcdefg", 
        "PasswordLastUsed": "2020-01-25T01:16:10Z", 
        "CreateDate": "2019-12-10T02:55:57Z", 
        "UserId": "AAAAAAAAAAAAAAAAAA", 
        "Path": "/", 
        "Arn": "arn:aws:iam::123456789012:user/abcdefg"
    }
}

Recommended Posts

(Command conversion) MFA authentication in AWS CLI
AWS CLI installation procedure
Procedure memo to put AWS command line interface in CentOS6