Last active
August 25, 2023 15:52
-
-
Save huevos-y-bacon/9cc9c6bbda807648ee679165e706ec7e to your computer and use it in GitHub Desktop.
AWS Organizations - Get Org Tree
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 | |
# shellcheck disable=SC2086 | |
# This is the same as "set -eux" but also exits on pipefail. | |
# Also see https://gist.github.com/mohanpedala/1e2ff5661761d3abd0385e8223e16425?permalink_comment_id=3935570#set--e--u--x--o-pipefail | |
set -euo pipefail | |
ROOT=$(aws organizations list-roots | jq -r '.Roots[0].Id') | |
# Function to list accounts and organizational units at a given depth | |
function list_entities { | |
local parent_id="$1" | |
local depth="$2" | |
IFS=$'\n' | |
# Retrieve accounts | |
accounts=$(aws organizations list-accounts-for-parent \ | |
--parent-id "$parent_id" \ | |
--output json \ | |
--query "Accounts[*].{Id:Id, Name:Name}" \ | |
| jq -r '.[] | "\(.Id)~\(.Name)"') | |
# Print accounts at the current depth | |
for account in $accounts; do | |
IFS="~" read -ra parts <<< "$account" | |
account_id="${parts[0]}" | |
account_name="${parts[1]}" | |
echo "$(printf '%*s' $depth) Account: $account_name ($account_id)" | |
done | |
# Retrieve organizational units | |
ous=$(aws organizations list-organizational-units-for-parent \ | |
--parent-id "$parent_id" \ | |
--output json \ | |
--query "OrganizationalUnits[*].{Id:Id, Name:Name}" \ | |
| jq -r '.[] | "\(.Id)~\(.Name)"') # Convert to a list of strings with the format "id~name" | |
# Print OUs at the current depth | |
for ou in $ous; do | |
IFS="~" read -ra parts <<< "$ou" | |
ou_id="${parts[0]}" | |
ou_name="${parts[1]}" | |
echo "$(printf '%*s' $depth) OU: $ou_name ($ou_id)" | |
list_entities "$ou_id" "$((depth + 4))" | |
done | |
} | |
# Start listing from the root | |
echo "AWS Organization Tree:" | |
list_entities "${ROOT}" 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment