Skip to content

Instantly share code, notes, and snippets.

@ogavrisevs
Created July 29, 2015 16:36
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
  • Save ogavrisevs/2debdcb96d3002a9cbf2 to your computer and use it in GitHub Desktop.
Save ogavrisevs/2debdcb96d3002a9cbf2 to your computer and use it in GitHub Desktop.
Script to generate AWS STS token
#!/bin/bash
#
# Sample for getting temp session token from AWS STS
#
# aws --profile youriamuser sts get-session-token --duration 3600 \
# --serial-number arn:aws:iam::012345678901:mfa/user --token-code 012345
#
# Based on : https://github.com/EvidentSecurity/MFAonCLI/blob/master/aws-temp-token.sh
#
AWS_CLI=`which aws`
if [ $? -ne 0 ]; then
echo "AWS CLI is not installed; exiting"
exit 1
else
echo "Using AWS CLI found at $AWS_CLI"
fi
if [ $# -ne 1 ]; then
echo "Usage: $0 <MFA_TOKEN_CODE>"
echo "Where:"
echo " <MFA_TOKEN_CODE> = Code from virtual MFA device"
exit 2
fi
AWS_USER_PROFILE=userName
AWS_2AUTH_PROFILE=2auth
ARN_OF_MFA=GAKTxxxxxxxxxx
MFA_TOKEN_CODE=$1
DURATION=129600
echo "AWS-CLI Profile: $AWS_CLI_PROFILE"
echo "MFA ARN: $ARN_OF_MFA"
echo "MFA Token Code: $MFA_TOKEN_CODE"
set -x
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< \
$( aws --profile $AWS_USER_PROFILE sts get-session-token \
--duration $DURATION \
--serial-number $ARN_OF_MFA \
--token-code $MFA_TOKEN_CODE \
--output text | awk '{ print $2, $4, $5 }')
echo "AWS_ACCESS_KEY_ID: " $AWS_ACCESS_KEY_ID
echo "AWS_SECRET_ACCESS_KEY: " $AWS_SECRET_ACCESS_KEY
echo "AWS_SESSION_TOKEN: " $AWS_SESSION_TOKEN
if [ -z "$AWS_ACCESS_KEY_ID" ]
then
exit 1
fi
`aws --profile $AWS_2AUTH_PROFILE configure set aws_access_key_id "$AWS_ACCESS_KEY_ID"`
`aws --profile $AWS_2AUTH_PROFILE configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY"`
`aws --profile $AWS_2AUTH_PROFILE configure set aws_session_token "$AWS_SESSION_TOKEN"`
~/.aws/config
[default]
region = eu-west-1
~/.aws/credentials
[userName]
aws_access_key_id: AxxxxxxxxxxxxxxxxxQ
aws_secret_access_key: hxxxxxxxxxxxxxxxxxx4
[2auth]
aws_access_key_id = AxxxxxxxxxxxxxxxxxA
aws_secret_access_key = pxxxxxxxxxxxxxxxxxxxxxy
aws_session_token = AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxF
$ aws --profile 2auth ec2 describe-instances
@frasergr
Copy link

I'd been using a variation of this script for a few years but recently wanted to have it integrated with other scripts I have for interacting with AWS. I spent some time with GPT4 and have come up with this which you or others may be interested to try:

https://gist.github.com/frasergr/498640e09feb4e25ea7536cd21c195cb

@gitjonez
Copy link

Thanks for this! I used a function (and gave you credit)
https://gist.github.com/gitjonez/ee7962a4f38088ccd7fe5604e034e3cd

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