Skip to content

Instantly share code, notes, and snippets.

@flaxhofr
Last active December 6, 2022 03:42
Show Gist options
  • Save flaxhofr/642c3364c3cbd53e6e20e85342a0fcce to your computer and use it in GitHub Desktop.
Save flaxhofr/642c3364c3cbd53e6e20e85342a0fcce to your computer and use it in GitHub Desktop.
aws sso auth utility
#!/bin/bash
export AWS_DEFAULT_REGION=$(aws configure get region)
export AWS_ACCOUNT_ID=$(aws configure get sso_account_id)
export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key)
export AWS_SESSION_TOKEN=$(aws configure get aws_session_token)
export AWS_DEFAULT_OUTPUT=json
export AWS_REGION=${AWS_DEFAULT_REGION}
export AWS_DEFAULT_PROFILE=default
export AWS_PROFILE=${AWS_DEFAULT_PROFILE}
#!/bin/bash
# NOTE requires aws cli V2 is installed locally. see https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
aws:sso:creds() {
local profile="${AWS_PROFILE:-"default"}"
local account_id="$(aws configure get sso_account_id --profile "${profile}")"
local role_name="$(aws configure get sso_role_name --profile "${profile}")"
local region="$(aws configure get region --profile "${profile}")"
local start_url="$(aws configure get sso_start_url --profile "${profile}")"
if [ -z "$start_url" ]; then
echo "did not find sso_start_url in profile ${profile}"
exit 1
fi
local cache_file="${HOME}/.aws/sso/cache/$(echo -n "$start_url" | sha1sum | awk '{print $1}').json"
if [ ! -f "$cache_file" ]; then
echo "sso creds not found. are you logged into AWS SSO?"
echo "aws sso login --profile \"${profile}\""
exit 1
fi
local access_token=$(jq -r .accessToken "${cache_file}")
vars=$(
aws sso get-role-credentials \
--account-id "${account_id}" \
--role-name "${role_name}" \
--region "${region:-us-east-1}" \
--access-token "${access_token}" \
--no-sign-request \
--output json |
jq -r '.roleCredentials |
{
"AWS_ACCESS_KEY_ID": .accessKeyId,
"AWS_SECRET_ACCESS_KEY": .secretAccessKey,
"AWS_SESSION_TOKEN": .sessionToken,
"AWS_CREDENTIALS_EXPIRATION": (.expiration / 1000 | todate)
}'
)
for s in $(echo $vars | jq -r "to_entries|map(\"\(.key)=\(.value)\")|.[]"); do
echo $s
local key=$(echo $s | cut -d "=" -f 1 | awk '{print tolower($0)}')
local val=$(echo $s | cut -d "=" -f 2)
aws configure set $key $val
export $s
done
}
aws:sso:login() {
aws sso login
aws:sso:creds
}
aws:sso:switch() {
aws configure sso
aws:sso:creds
}
aws:ecr:login() {
aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login \
--username AWS \
--password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment