Skip to content

Instantly share code, notes, and snippets.

@davewongillies
Forked from mbainter/aws_config.fish
Last active July 22, 2021 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davewongillies/5f3ec1a271b7fd5b0e1fb24eb761c0ba to your computer and use it in GitHub Desktop.
Save davewongillies/5f3ec1a271b7fd5b0e1fb24eb761c0ba to your computer and use it in GitHub Desktop.
Fish shell function to set your AWS credentials with MFA
function aws_config
if not fgrep -q "[$argv]" ~/.aws/credentials
echo "Please specify a valid profile."
else
set token_expired false
if test $AWS_SESSION_EXPIRY
set now (date +%s)
# WARNING: this date command only works with GNU date
set expiry (date -d $AWS_SESSION_EXPIRY +%s)
if [ $now -gt $expiry ]
set -e AWS_SESSION_EXPIRY
set token_expired true
end
end
if [ $token_expired = true ]
set -e AWS_ACCESS_KEY_ID
set -e AWS_SECRET_ACCESS_KEY
set -e AWS_SESSION_TOKEN
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"
set duration "43200"
echo "Please enter your MFA token for $mfarn:"
read -l mfa_token
set aws_cli (aws --profile=$argv sts get-session-token \
--serial-number="$mfarn" \
--token-code=$mfa_token \
--duration-seconds $duration \
--output text \
--query 'Credentials | join (`;`,values({ AccessKeyId: join(``, [`set -Ux AWS_ACCESS_KEY_ID `,AccessKeyId]), SecretAccessKey:join(``, [`set -Ux AWS_SECRET_ACCESS_KEY `,SecretAccessKey]), SessionToken:join(``, [`set -Ux AWS_SESSION_TOKEN `,SessionToken]), Expiration:join(``, [`set -Ux AWS_SESSION_EXPIRY `,Expiration]) }))' )
fish -c $aws_cli
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment