Last active
October 10, 2024 16:01
-
-
Save spencerdcarlson/e66be7f4219a676b30af43dbc336a66c to your computer and use it in GitHub Desktop.
AWS SSO Login Script
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
#!/usr/bin/env bash | |
set -euo pipefail | |
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 with_error () { | |
local message="${1}" | |
log "${message}" true | |
exit 1 | |
} | |
function get_account () { | |
local profile=${1:-$PROFILE} | |
local account=-1 | |
account=$(aws sts get-caller-identity --query "Account" --profile "${profile}" --output text 2>/dev/null) | |
[ $? -eq 0 ] && [ "${account}" -ne -1 ] && echo "${account}" | |
return 0 | |
} | |
TEMP_FILE="" | |
function login () { | |
local profile=${1:-$PROFILE} | |
TEMP_FILE=$(mktemp) | |
trap 'rm -f "${TEMP_FILE}"' EXIT | |
# run in background, because output is blocked by web browser | |
aws sso login --profile "${profile}" > "${TEMP_FILE}" 2>&1 & | |
while [ ! -s "${TEMP_FILE}" ]; do | |
sleep 0.1 | |
done | |
local code="" | |
code=$(cat "${TEMP_FILE}" | tail -1) | |
if [[ "${code}" =~ ^[A-Z]{4}-[A-Z]{4}$ ]]; then | |
echo "${code}" | |
return 0 | |
else | |
log "Invalid authorization code. code=${code}, file=${TEMP_FILE}" true | |
return 1 | |
fi | |
} | |
if ! command -v aws >/dev/null 2>&1; then with_error "'aws' is required."; fi | |
CURRENT_ACCOUNT=$(get_account) | |
# Login if there is no session | |
if [ $? -eq 0 ] && [ -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 | |
AUTH_CODE=$(login) | |
if [ $? -eq 0 ] && [ -n "${AUTH_CODE}" ]; then | |
log "Authorization Code: ${AUTH_CODE}" | |
if command -v say >/dev/null 2>&1; then | |
echo "${AUTH_CODE}" | awk '{ for(i=1; i<=length($0); i++) print substr($0, i, 1) }' | say | |
fi | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment