Created
June 25, 2023 17:37
-
-
Save kujjwal02/fd61085ad78902cd07fad9c15517306f to your computer and use it in GitHub Desktop.
fish shell function to authenticate aws cli using mfa token
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_mfa | |
set code $argv[1] | |
set serial_number "<add mfa serial here>" | |
# Check if token code is provided | |
if test -z $code | |
set_color red | |
echo "Token code not provided. Please provide the token code as an argument." | |
set_color normal | |
echo "Usage: aws_mfa <token-code> [additional arguments]" | |
return 1 | |
end | |
# Run the AWS CLI command to get the session token | |
# set sts_command "aws sts get-session-token --serial-number $serial_number --token-code $code" | |
set -l sts_args --serial-number $serial_number --token-code $code $argv[2..-1] | |
set sts_command "aws sts get-session-token" $sts_args | |
echo "Executing AWS STS command:" | |
echo $sts_command | |
set -l response (eval $sts_command) | |
# set -l response (aws sts get-session-token --serial-number $serial_number --token-code $code) | |
# Check if the AWS CLI command succeeded | |
if test $status -ne 0 | |
set_color red | |
echo "Failed to retrieve AWS session token. Please verify the token code and try again." | |
set_color normal | |
return 1 | |
end | |
# Extract the necessary values from the response | |
set access_key (echo $response | jq -r '.Credentials.AccessKeyId') | |
set secret_key (echo $response | jq -r '.Credentials.SecretAccessKey') | |
set session_token (echo $response | jq -r '.Credentials.SessionToken') | |
echo "" | |
set_color yellow | |
echo "AWS_ACCESS_KEY_ID=$access_key" | |
echo "AWS_SECRET_ACCESS_KEY=$secret_key" | |
echo "AWS_SESSION_TOKEN=$session_token" | |
set_color normal | |
echo "" | |
# Set the environment variables with the obtained credentials | |
set -xg AWS_ACCESS_KEY_ID $access_key | |
set -xg AWS_SECRET_ACCESS_KEY $secret_key | |
set -xg AWS_SESSION_TOKEN $session_token | |
set_color green | |
echo "AWS credentials have been set." | |
set_color normal | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
place the file in
~/.config/fish/functions
folder