Skip to content

Instantly share code, notes, and snippets.

@drewwells
Created December 19, 2022 18:36
Show Gist options
  • Save drewwells/a64ec3803db0ccaea606d7666c9cbd03 to your computer and use it in GitHub Desktop.
Save drewwells/a64ec3803db0ccaea606d7666c9cbd03 to your computer and use it in GitHub Desktop.
aws_creds() {
local profile="${1:-${AWS_PROFILE}}"
local account_id="$(aws configure get sso_account_id --profile "${profile}")" \
role_name="$(aws configure get sso_role_name --profile "${profile}")" \
region="$(aws configure get region --profile "${profile}")" \
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 ;
echo "aws sso login --profile \"${profile}\""
exit 1
fi
local access_token=$(jq -r .accessToken "${cache_file}")
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 --arg p "${AWS_PROFILE}" -r '.roleCredentials |
{
"aws_access_key_id": .accessKeyId,
"aws_secret_access_key": .secretAccessKey,
"aws_session_token": .sessionToken,
"aws_credentials_expiration": (.expiration / 1000 | todate)
} | keys[] as $k | "aws configure set --profile \($p) \($k) \"\(.[$k])\";\n"'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment