AWS CLI via MFA

image



Next, there will be instructions on how to configure AWS MFA, and then install and configure AWS CLI.



Unfortunately, this obligatory procedure took me half a day. So that other insecure AWS users;), like myself, do not waste precious time on trivial, I decided to draw up an instruction.



Even for a sandbox account, setting up MFA is usually a mandatory requirement. It is so with us.



Configuring MFA



  1. Install a compatible mobile app
  2. Go to AWS Console
  3. My Security Credentials -> Assign MFA Device

  4. Virtual MFA Device

  5. Follow the instructions on the screen



  6. Virtual Appliance Ready



Installing AWS CLI



https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html



Setting up a named profile



https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html



  1. My Security Credentials -> Create access key

  2. Copy the key to your clipboard. You will need it in the next step.
  3. $ aws configure --profile <your profile name>


AWS CLI via MFA



  1. Copy ARN of the virtual device

  2. aws sts get-session-token --profile < > --serial-number <ARN > --token-code < >

    One-time password must be taken from the previously configured mobile application.
  3. The command will output JSON, the individual fields of which must be substituted into the corresponding environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN


I decided to automate via ~/.bash_profile

This script requires jq to parse JSON .



#!/usr/bin/env bash

aws_login() {
    session=$(aws sts get-session-token "$@")
    echo "${session}"
    AWS_ACCESS_KEY_ID=$(echo "${session}" | jq -r '.Credentials.AccessKeyId')
    export AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY=$(echo "${session}" | jq -r '.Credentials.SecretAccessKey')
    export AWS_SECRET_ACCESS_KEY
    AWS_SESSION_TOKEN=$(echo "${session}" | jq -r '.Credentials.SessionToken')
    export AWS_SESSION_TOKEN
}

alias aws-login-dev='aws_login --profile < dev > --serial-number <ARN  > --token-code '
alias aws-login-prod='aws_login --profile < prod > --serial-number <ARN  > --token-code '


Using:



$ aws-login-dev < >


I hope this instruction will help you avoid lengthy wanderings in the official documentation;)




All Articles