DEV Community

Cover image for Using a YubiKey with AWS CLI Sessions
Micah Carrick
Micah Carrick

Posted on

Using a YubiKey with AWS CLI Sessions

This is the bash script I use with yubikey-manager CLI (ykman) to create a session for the AWS CLI using a YubiKey as a MFA device. This configuration is specifically for using short-term credentials.

Using the script avoids having to copy/paste the code obtained from the YubiKey to the get-session-token command.

Requirements:

~/.aws/config

[profile my-session] [profile my-profile] source_profile = my-session 
Enter fullscreen mode Exit fullscreen mode

The script will first use ykman which pauses and waits for the button on the YubiKey to be pressed. This produces a code that is passed to get-session-token.

#!/bin/env bash # MFA_SERIAL_ARN="arn:aws:iam::[ACCOUNT_ID]:mfa/[IAM_USER]" MFA_SERIAL_ARN="arn:aws:iam::111111111111:mfa/jane.doe" USER_PROFILE="my-profile" SESSION_PROFILE="my-session" echo "Fetching code from Yubikey device" mfa_code=$(ykman oath accounts code --single $MFA_SERIAL_ARN) echo "Creating session (code=$mfa_code)" sts=$(aws sts get-session-token \ --duration 14400 \ --serial-number $MFA_SERIAL_ARN \ --token-code $mfa_code \ --profile $USER_PROFILE) access_key_id=`echo $sts | jq -r '.Credentials.AccessKeyId'` secret_access_key=`echo $sts | jq -r '.Credentials.SecretAccessKey'` session_token=`echo $sts | jq -r '.Credentials.SessionToken'` expiration=`echo $sts | jq -r '.Credentials.Expiration'` echo "Session expires on: $expiration" aws configure set aws_access_key_id $access_key_id \ --profile $SESSION_PROFILE aws configure set aws_secret_access_key $secret_access_key \ --profile $SESSION_PROFILE aws configure set aws_session_token $session_token \ --profile $SESSION_PROFILE 
Enter fullscreen mode Exit fullscreen mode

The output of the script would look something like this:

Fetching code from YubiKey device Touch your YubiKey... Creating session (code=123456) Session expires on: 2025-02-23T22:12:29+00:00 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)