1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

(コマンド化)AWS CLIにおけるMFA認証

Posted at

概要

AWSマネジメントコンソールにアクセスするためのIAMユーザーにMFAを設定している場合、
同ユーザーにてAWS CLIを使う時にもMFAによる認証が必要になるけど、
すぐに忘れちゃうのでコマンド化した。

ざっくりセットアップ手順

  1. アクセスキーの作成(まだやってない人は)
  2. .bashrcに以下追記
  3. ログインし直す 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
}

使い方

AWSCLIINIT

  • 中でaws configureをやってるので必要に応じて入力
  • mfaを聞かれるので入力
$ 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
$

エラーがでなければ認証成功。環境変数にトークンなどがセットされます。

こんな感じ。

MFA認証前


$ 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

本コマンド利用時


$ 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"
    }
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?