Created
October 28, 2022 08:44
-
-
Save rollwagen/30806ec113e062741768d64558833678 to your computer and use it in GitHub Desktop.
Bash script switching accounts in an AWS orginazation
This file contains 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
#!/bin/bash | |
START_URL="https://d-0123456789.awsapps.com/start#/" | |
REGION="eu-central-1" | |
HASH="$(echo -n "$START_URL" | sha1sum | cut -d' ' -f1)" | |
CACHE_FILENAME="$HASH.json" | |
SSO_TOKEN=$(jq -r '.accessToken' < ~/.aws/sso/cache/"$CACHE_FILENAME") | |
ACCOUNT_ID=$(aws sso list-accounts --region "$REGION" --access-token "$SSO_TOKEN" | jq -r '.accountList[] | .accountName + " - " + .accountId' | fzf | cut -d" " -f3) | |
if [ -z "$ACCOUNT_ID" ]; | |
then | |
exit | |
fi | |
ROLE="ViewOnlyAccess" | |
if aws sso list-account-roles --region "$REGION" --access-token "$SSO_TOKEN" --account-id "$ACCOUNT_ID" | grep -q AdministratorAccess | |
then | |
ROLE="AdministratorAccess" | |
fi | |
ROLE_CREDENTIALS=$(aws sso get-role-credentials --region "$REGION" --account-id "$ACCOUNT_ID" --role-name "$ROLE" --access-token "$SSO_TOKEN") | |
ACCESS_KEY_ID="$(echo "$ROLE_CREDENTIALS" | jq -r '.roleCredentials.accessKeyId')" | |
SECRET_ACCESS_KEY="$(echo "$ROLE_CREDENTIALS" | jq -r '.roleCredentials.secretAccessKey')" | |
SESSION_TOKEN="$(echo "$ROLE_CREDENTIALS" | jq -r '.roleCredentials.sessionToken')" | |
echo "export AWS_ACCESS_KEY_ID=$ACCESS_KEY_ID; export AWS_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY; export AWS_SESSION_TOKEN=$SESSION_TOKEN" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment