Created
July 12, 2023 10:04
-
-
Save apriady/7946d9c468f681d6c70886154f255d96 to your computer and use it in GitHub Desktop.
Bash script to generate AWS_SESSION_TOKEN and set to target profile (Include integration with 1password)
This file contains hidden or 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
#!/bin/bash | |
AWS_BASE_PROFILE=base-profile | |
AWS_TARGET_PROFILE=target-profile | |
ARN_OF_MFA=arn:aws:iam::1234567890:mfa/mfa-device | |
DURATION=129600 | |
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 ] && [ -z ${ONEPASS_ACCOUNT} ] | |
then | |
echo "Usage: $0 <MFA_TOKEN_CODE>" | |
echo "Where:" | |
echo " <MFA_TOKEN_CODE> = Code from virtual MFA device" | |
exit 2 | |
fi | |
if [[ ${ONEPASS_ACCOUNT} && -z ${ONEPASS_ENTRY} ]] | |
then | |
echo "You have set ONEPASS_ACCOUNT environment variable, but forget to set ONEPASS_ENTRY!" | |
exit 2 | |
fi | |
if [[ ${ONEPASS_ACCOUNT} && ${ONEPASS_ENTRY} ]] | |
then | |
eval $(op signin --account ${ONEPASS_ACCOUNT}) | |
MFA_TOKEN_CODE=$(op item get "${ONEPASS_ENTRY}" --otp) | |
op signout | |
else | |
MFA_TOKEN_CODE=$1 | |
fi | |
echo "AWS-CLI Profile: $AWS_BASE_PROFILE" | |
echo "MFA ARN: $ARN_OF_MFA" | |
echo "MFA Token Code: $MFA_TOKEN_CODE" | |
read AWS_ACCESS_KEY_ID_TEMP AWS_SECRET_ACCESS_KEY_TEMP AWS_SESSION_TOKEN_TEMP <<< \ | |
$( aws --profile $AWS_BASE_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_TEMP | |
echo "AWS_SECRET_ACCESS_KEY: " $AWS_SECRET_ACCESS_KEY_TEMP | |
echo "AWS_SESSION_TOKEN: " $AWS_SESSION_TOKEN_TEMP | |
if [ -z "$AWS_ACCESS_KEY_ID_TEMP" ] | |
then | |
exit 1 | |
fi | |
aws --profile $AWS_TARGET_PROFILE configure set aws_access_key_id "$AWS_ACCESS_KEY_ID_TEMP" | |
aws --profile $AWS_TARGET_PROFILE configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY_TEMP" | |
aws --profile $AWS_TARGET_PROFILE configure set aws_session_token "$AWS_SESSION_TOKEN_TEMP" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment