Skip to content

Instantly share code, notes, and snippets.

@umihico
Last active June 25, 2022 12:50
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 umihico/3a19974ccb251a01dc870fe39b09749f to your computer and use it in GitHub Desktop.
Save umihico/3a19974ccb251a01dc870fe39b09749f to your computer and use it in GitHub Desktop.
Sign in AWS console by CLI credentials
# https://gist.github.com/umihico/3a19974ccb251a01dc870fe39b09749f
function aws-sub() {
aws-main --incognito
}
function aws-main() {
if [ "$1" = "--incognito" ]; then # Sign-out current user
open -na 'Google Chrome' --args --incognito "https://signin.aws.amazon.com/oauth?Action=logout&redirect_uri=https://aws.amazon.com" # Mac, OSX
else
open -a 'Google Chrome' "https://signin.aws.amazon.com/oauth?Action=logout&redirect_uri=https://aws.amazon.com" # Mac, OSX
fi
REGION=$(aws configure get region)
AWS_IDENTITY=$(aws sts get-caller-identity | jq -cr)
echo Executing as $(jq -n --argjson data "$AWS_IDENTITY" '$data.UserId') in $(jq -n --argjson data "$AWS_IDENTITY" '$data.Account')
LOGIN_USERNAME=$(jq -nr --argjson data "$AWS_IDENTITY" '$data.Arn | split("/")[-1]')-$(date +%s)-magiclink
ROLE_ARN=$(aws configure get role_arn || echo "")
if [ -z "$ROLE_ARN" ]; then
# Use get-federation-token command if current profile is IAM user
TEMP_CRED_JSON=$(aws sts get-federation-token \
--name ${LOGIN_USERNAME:0:32} \
--policy '{"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]}' \
| jq -cr)
else
# Use assume-role command if current profile has role_arn attribute
TEMP_CRED_JSON=$(aws sts assume-role --role-arn $ROLE_ARN --role-session-name ${LOGIN_USERNAME:0:32} | jq -cr)
fi
ENCODED_SESSION=$(jq -c -r -n -R -s --argjson data "$TEMP_CRED_JSON" '{"sessionId":$data.Credentials.AccessKeyId,"sessionKey":$data.Credentials.SecretAccessKey,"sessionToken":$data.Credentials.SessionToken}' | jq -Rr '. | "Session="+.')
SIGNIN_TOKEN=$(curl -sG \
--data-urlencode "Action=getSigninToken" \
--data-urlencode "SessionDuration=1800" \
--data-urlencode "$ENCODED_SESSION" \
https://signin.aws.amazon.com/federation | jq -r .SigninToken)
CONSOLE_URL="https://${REGION}.console.aws.amazon.com/"
LOGIN_URL="https://signin.aws.amazon.com/federation?Action=login&Destination=${CONSOLE_URL}&SigninToken=${SIGNIN_TOKEN}"
if [ "$1" = "--incognito" ]; then
open -na 'Google Chrome' --args --incognito "$LOGIN_URL" # Mac, OSX
else
open -a 'Google Chrome' "$LOGIN_URL" # Mac, OSX
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment