Last active
February 24, 2024 15:51
-
-
Save mbainter/b38a4cb411c0b5c1bae6 to your computer and use it in GitHub Desktop.
Fish shell function to set your AWS credentials with MFA for use with Terraform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function aws_config | |
if not fgrep -q "[$argv]" ~/.aws/credentials | |
echo "Please specify a valid profile." | |
else | |
set -e AWS_ACCESS_KEY | |
set -e AWS_SECRET_KEY | |
set -g -x ATLAS_TOKEN (awk "/\[$argv\]/,/^\$/ { if (\$1 == \"atlas_token\") { print \$3 }}" ~/.aws/credentials) | |
set account (awk "/\[$argv\]/,/^\$/ { if (\$1 == \"account_id\") { print \$3 }}" ~/.aws/credentials) | |
set username (awk "/\[$argv\]/,/^\$/ { if (\$1 == \"username\") { print \$3 }}" ~/.aws/credentials) | |
set mfarn "arn:aws:iam::$account:mfa/$username" | |
echo "Please enter your MFA token:" | |
read -l mfa_token | |
set json (aws --profile=$argv sts get-session-token --serial-number="$mfarn" --token-code=$mfa_token) | |
set -g -x AWS_ACCESS_KEY_ID (echo $json | jq -r '.Credentials.AccessKeyId') | |
set -g -x AWS_SECRET_ACCESS_KEY (echo $json | jq -r '.Credentials.SecretAccessKey') | |
set -g -x AWS_SESSION_TOKEN (echo $json | jq -r '.Credentials.SessionToken') | |
end | |
end |
Looking at the source for terraform, it looks like it supports using AWS_SESSION_TOKEN as well, which is more compatible with other utilities (like terraforming). Updated to take this into account.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Depends on having jq and the aws cli installed, and leverages the credentials ini file's ability to store arbitrary variable data. Just setup a profile there with your username and account number, and then run aws_config. It will prompt for an MFA credential value and then set your token.
Uses the default setting of 12 hours for the token lifetime, after which you can just run the command again.
If you're using terraform, this will setup the environment in a way that will allow you to run API commands that require you to be authenticated with MFA.