Skip to content

Instantly share code, notes, and snippets.

@spencerdcarlson
Last active October 10, 2024 16:01
Show Gist options
  • Save spencerdcarlson/e66be7f4219a676b30af43dbc336a66c to your computer and use it in GitHub Desktop.
Save spencerdcarlson/e66be7f4219a676b30af43dbc336a66c to your computer and use it in GitHub Desktop.
AWS SSO Login Script
#!/usr/bin/env bash
PROFILE=${1}
ACCOUNT_ID=${2}
function log () {
local message="${1}"
local is_error="${2:-false}"
if [[ "${is_error}" == true ]]; then
echo "$(date +"%Y-%m-%d %H:%M:%S") - ERROR: ${message}" >&2
else
echo "$(date +"%Y-%m-%d %H:%M:%S") - INFO: ${message}"
fi
}
function get_account () {
local profile=${PROFILE}
local account=$(aws sts get-caller-identity --query "Account" --profile "${profile}" --output text 2>/dev/null)
account=${account:--1}
if [ "${account}" -ne -1 ]; then
CURRENT_ACCOUNT="${account}"
echo "${CURRENT_ACCOUNT}"
fi
return 0
}
function login () {
local profile=${PROFILE}
local sout=$(mktemp)
# run in background, because output is blocked by web browser
aws sso login --profile "${profile}" > "${sout}" 2>&1 &
while [ ! -s "${sout}" ]; do
sleep 0.1
done
local code=$(cat "${sout}" | tail -1)
echo "Authorization Code: ${code}"
rm "${sout}"
if [[ "${code}" =~ ^[A-Z]{4}-[A-Z]{4}$ ]]; then
AUTH_CODE="${code}"
echo "${AUTH_CODE}"
return 0
fi
return 1
}
get_account > /dev/null 2>&1
# Login if there is no session
if [ -n "${CURRENT_ACCOUNT}" ]; then
log "Currently logged into ${CURRENT_ACCOUNT}"
else
log "No active session. Starting SSO flow..."
fi
# Login if currently not logged in or logged into a diffeent account
if [ "${CURRENT_ACCOUNT:--1}" -ne "${ACCOUNT_ID}" ]; then
login > /dev/null 2>&1
if [ $? -eq 0 ] && [ -n "${AUTH_CODE}" ]; then
log "Authorization Code: ${AUTH_CODE}"
echo "${AUTH_CODE}" | awk '{ for(i=1; i<=length($0); i++) print substr($0, i, 1) }' | say
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment