AWS CLI using 1Password MFA

Tom Lous
2 min readSep 18, 2023

I was given access to an AWS environment, but as a developer I prefer to use the CLI above the IMHO horrible AWS UI.
Haven’t used AWS in a while (many clients are Azure focussed) I got some weird warnings trying to access the cluster

An error occurred (AccessDeniedException) when calling the ListClusters operation: User: arn:aws:iam::[num]:user/[user] is not authorized to perform: ecs:ListClusters on resource: * with an explicit deny in an identity-based policy

The owner told me that I had admin level access on all the neccesary resources, so I was a bit dumbfounded.

After some research I found out that MFA was also enabled for the CLI tools, so this was the reason for that error.

Trying to setup MFA for your CLI can be tedious process, but with the 1password CLI things can be fairly automated.

This is the script I use to generate a session token that will last for 36 hours.

unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN

OTP_ID=$1
OTP=$(op item get $OTP_ID --otp)
DEVICE_ID=$(aws iam list-mfa-devices | jq -r '.MFADevices[0].SerialNumber')

RESULT=$(aws sts get-session-token --serial-number $DEVICE_ID --duration-seconds 129600 --token-code $OTP)

export AWS_ACCESS_KEY_ID=$(echo $RESULT | jq -r…

--

--

Tom Lous
Tom Lous

Written by Tom Lous

Freelance Data & ML Engineer | husband + father of 2 | #Spark #Scala #ZIO#BigData #ML #Kafka #Airflow #Kubernetes | Shodan Aikido

No responses yet