Skip to content

Instantly share code, notes, and snippets.

@1davidmichael
Last active June 20, 2023 14:23
Show Gist options
  • Save 1davidmichael/9053096f8017b51c646e7b85bdc91b4a to your computer and use it in GitHub Desktop.
Save 1davidmichael/9053096f8017b51c646e7b85bdc91b4a to your computer and use it in GitHub Desktop.
Bash script to get MFA authenticated AWS credentials
[credential]
helper = !aws codecommit credential-helper $@
UseHttpPath = true

Bash script to get MFA authenticated AWS credentials

  1. Add .gitconfig setting to any CodeCommit repo for checking out with HTTPS credentials from the AWS CLI
  2. Add the aws_cli_mfa.sh to your path and then invoke it in the example below
aws_cli_mfa.sh example-profile 123456

# Copy the output values and paste back into terminal to use credentials with MFA
#!/bin/bash -euo pipefail
PROFILE_NAME="$1"
MFA_TOKEN_CODE="$2"
account_id=$(aws sts get-caller-identity \
--query Account \
--output text \
--profile $PROFILE_NAME)
mfa_serial=$(aws iam list-mfa-devices \
--query 'MFADevices[0].SerialNumber' \
--output text \
--profile $PROFILE_NAME)
# This script will prompt for your MFA token code and then set the AWS CLI environment variables
output=$(aws sts get-session-token \
--profile wasatch-master \
--serial-number $mfa_serial \
--token-code $MFA_TOKEN_CODE)
echo "export AWS_ACCESS_KEY_ID=$(echo $output | jq -r .Credentials.AccessKeyId)"
echo "export AWS_SECRET_ACCESS_KEY=$(echo $output | jq -r .Credentials.SecretAccessKey)"
echo "export AWS_SESSION_TOKEN=$(echo $output | jq -r .Credentials.SessionToken)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment