Skip to content

Instantly share code, notes, and snippets.

@gildas
Last active January 6, 2022 18:28
Show Gist options
  • Save gildas/6f1d2fce9117791ae4de5a0c17f761cc to your computer and use it in GitHub Desktop.
Save gildas/6f1d2fce9117791ae4de5a0c17f761cc to your computer and use it in GitHub Desktop.
Starts a new AWS Session with an MFA Code
#!/usr/bin/env bash
function aws-auth() {
token_code=$1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SESSION_TOKEN_EXPIRATION
aws_identity=$(aws sts get-caller-identity --output json)
aws_account=$(echo "$aws_identity" | jq -r .Account)
aws_user=$(echo "$aws_identity" | jq -r .Arn | cut -d/ -f2)
aws_arn="arn:aws:iam::${aws_account}:mfa/${aws_user}"
creds=$(aws sts get-session-token --serial-number "$aws_arn" --token-code $token_code --duration-seconds 129600 --output json)
export AWS_ACCESS_KEY_ID=$(echo "$creds" | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "$creds" | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "$creds" | jq -r .Credentials.SessionToken)
export AWS_SESSION_TOKEN_EXPIRATION=$(echo "$creds" | jq -r .Credentials.Expiration)
unset aws_identity creds aws_account aws_user aws_arn
}
@gildas
Copy link
Author

gildas commented Sep 28, 2021

This function should be sourced in your environment

. ./aws-auth.sh

Or included in your .bashrc/.zshrc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment