From bf0d2d32e2b9639ad2e770a4b5ea8b161258dd2c Mon Sep 17 00:00:00 2001 From: mgeeky Date: Thu, 16 May 2019 11:00:46 +0200 Subject: [PATCH] Error-proofing get-session-creds script. --- .../aws/get-session-creds-in-config-format.sh | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/clouds/aws/get-session-creds-in-config-format.sh b/clouds/aws/get-session-creds-in-config-format.sh index fbf2c27..0777351 100644 --- a/clouds/aws/get-session-creds-in-config-format.sh +++ b/clouds/aws/get-session-creds-in-config-format.sh @@ -8,21 +8,26 @@ # +# -------------------------- # Configure below variables. # + +# This profile name must be different among any other profiles oyu have defined in your +# config and credentials file. PROFILE_NAME=your-profile-name ROLE_NAME=Your_Role_Name ROLE_ARN=arn:aws:iam:::role/$ROLE_NAME -# If you leave this field empty - one will be deduced from `aws sts get-caller-identity` output +# If you leave this field empty - it will be deduced from `aws sts get-caller-identity` output #SERIAL_MFA=arn:aws:iam:::mfa/ SERIAL_MFA= -# Values possible range: 900-43200 +# Duration in seconds. Values possible range: 900-43200 +# 1 hour - 3600, 2 hours - 7200, 3 hours - 10800, 6 hours - 21600, 12 hours - 43200 DURATION=42000 # -# ------------------------ +# -------------------------- # # Some times assume-role may return with an Access-Denied if there were no account authenticated @@ -30,7 +35,7 @@ DURATION=42000 out=$(aws sts get-caller-identity) if [ $? -ne 0 ]; then echo "[!] Could not get caller's identity: " - echo $out + echo "$out" exit 1 fi @@ -41,14 +46,27 @@ fi read -p "Type your AWS MFA Code: " code echo -out=$(aws sts assume-role --serial-number $SERIAL_MFA --role-arn $ROLE_ARN --role-session-name $ROLE_NAME --duration-seconds $DURATION --token-code $code) +out=$(aws sts assume-role --serial-number $SERIAL_MFA --role-arn $ROLE_ARN --role-session-name $ROLE_NAME --duration-seconds $DURATION --token-code $code 2>&1) if [ $? -eq 0 ]; then + valid=$(printf '%dh:%dm:%ds\n' $(($DURATION/3600)) $(($DURATION%3600/60)) $(($DURATION%60))) + echo "[+] Collected session credentials. They will be valid for: $valid. " + echo -e "\tPaste below lines to your '~/.aws/credentials' file:" + echo echo "[$PROFILE_NAME]" echo "$out" | python3 -c 'import sys,json; foo=json.loads(sys.stdin.read()); print("aws_access_key_id={}\naws_secret_access_key={}\naws_session_token={}".format(foo["Credentials"]["AccessKeyId"],foo["Credentials"]["SecretAccessKey"],foo["Credentials"]["SessionToken"]))' echo else echo "[!] Could not obtain assume-role session credentials:" - echo $out + echo "$out" + echo + out2=$(env | grep -E 'AWS_[^=]+') + if [[ "$out2" != "" ]]; then + echo "[!] Your command could fail because of pre-set AWS-related environment variables." + echo -e "\tPlease review them, correct any problems and re-launch that script." + echo + echo "$out2" + echo + fi exit 1 fi