Skip to content

Instantly share code, notes, and snippets.

@rounakdatta
Forked from ogavrisevs/aws-temp-token.sh
Last active July 9, 2020 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rounakdatta/6fa8c31d363e75b4a8ecd2b78c1e5451 to your computer and use it in GitHub Desktop.
Save rounakdatta/6fa8c31d363e75b4a8ecd2b78c1e5451 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=master
AWS_2AUTH_PROFILE=default
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 = ap-south-1
~/.aws/credentials
[master]
aws_access_key_id: AxxxxxxxxxxxxxxxxxQ
aws_secret_access_key: hxxxxxxxxxxxxxxxxxx4
[default]
region = ap-south-1
aws_access_key_id = AxxxxxxxxxxxxxxxxxA
aws_secret_access_key = pxxxxxxxxxxxxxxxxxxxxxy
aws_session_token = AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxF
$ aws --profile default ec2 describe-instances
OR
$ aws ec2 describe-instances
The to-be-written-profile has been kept as default to facilitate SDKs using the aws CLI effectively
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment