Use MFA on the CLI and execute awscli commands securely
To enhance security, you can enable multi-factor authenticantion (MFA) use also for issuing CLI commands. Manually obtaining the temporary tokens and setting them up as environment variables can be a hassle. I came up with this quick script to automate the job.
In the following script, you only have to replace
YOUR_MFA_ARN
with the MFA device you have configured in you security settings in your AWS IAM user.
Then you can either
source
or
execute
the script.
Here’s the bash script
aws-mfa-cli.sh
:
# !/bin/bash
set -e
# check if script has been sourced or executed
(return 0 2>/dev/null) && sourced=1 || sourced=0
MFA_DEVICE_ARN=YOUR_MFA_ARN
read -p "Please enter you MFA code: " MFA_CODE
echo "You entered '$MFA_CODE'"
echo aws --output text sts get-session-token \
--serial-number arn:aws:iam::661095214357:mfa/anmichel.rodriguez@annalect.com \
--token-code $MFA_CODE
CREDS=$(aws --output text sts get-session-token \
--serial-number $MFA_DEVICE_ARN \
--token-code $MFA_CODE)
echo $CREDS
KEY=$(echo $CREDS | cut -d" " -f2)
SECRET=$(echo $CREDS | cut -d" " -f4)
SESS_TOKEN=$(echo $CREDS | cut -d" " -f5)
echo "Key: $KEY"
echo "Secret: $SECRET"
echo "Session token: $SESS_TOKEN"
export AWS_ACCESS_KEY_ID=$KEY
export AWS_SECRET_ACCESS_KEY=$SECRET
export AWS_SESSION_TOKEN=$SESS_TOKEN
if [ $sourced -eq 1 ]; then
echo "Script was sourced."
else
echo "Script was executed, starting subshell."
bash -l
fi