Enabling an AWS IAM MFA via CLI
NB: Linebreaks (\
) have been added to the CLI commands for readability.
I am in the process of setting up an AWS account for my family and part of that initial setup is to create users and roles for family members. Everyone receives readonly privileges and has to assume an IAM to gain elevated privileges. The people who are allowed to assume these elevated privileges must have a valid MFA session.
But here's the rub: when the CFN stack is created, how does one assume the administrator IAM role when they initially login, since they haven't yet enabled an MFA on their account?
Using the initial user you've created you can do this easily with the CLI.
First you create a new virtual MFA device. The device name you give can be anything, but I suggest following the AWS best practice of naming it after the username of the user. It makes it easier to match the MFA device with the intended user. The outfile is a PNG file that can be viewed in your OS and scanned with your mobile QR Code reader (e.g. Google Authenticator or Authy).
aws iam create-virtual-mfa-device \
--virtual-mfa-device-name typicalrunt \
--outfile $HOME/QRCode.png \
--bootstrap-method QRCodePNG \
--region ca-central-1
What you receive back is a JSON payload with the SerialId of the MFA device created.
It is important to note that this creates the MFA device, but it does not assign it to someone automatically. Hmm, I wonder if this means I can share an MFA device with more than one IAM user?
Next you assign it to the IAM user.
aws iam enable-mfa-device \
--user-name typicalrunt \
--serial-number "arn:aws:iam::123456789012:mfa/typicalrunt" \
--authentication-code-1 12345 \
--authentication-code-2 67890 \
--region ca-central-1
The MFA device is now assigned to the IAM user and they can login again with their username/password/MFA, providing them with an MFA session token so that IAM role assumption to the privileged role will succeed.