Skip to content

Instantly share code, notes, and snippets.

@pommi
Forked from atheiman/get-accounts-recursive.sh
Created October 12, 2022 09:38
Show Gist options
  • Save pommi/0ff3b29853472768cfaae88531c895c1 to your computer and use it in GitHub Desktop.
Save pommi/0ff3b29853472768cfaae88531c895c1 to your computer and use it in GitHub Desktop.
Get all accounts within an AWS Organizations organizational unit recursively (all accounts nested under any child OUs)
#!/bin/bash
if [ -z "$1" ]; then
echo "Error - Usage: $0 <parent-id>"
exit 1
fi
set -eu
# set -x
get_accounts_recursive() {
INDENT=$(printf '=%.0s' $(seq $2))
aws organizations list-accounts-for-parent --parent-id "$1" | jq -r --arg INDENT "$INDENT" '.Accounts[] | "\($INDENT) \(.Name) (\(.Id))"' | sort
for ou in $(aws organizations list-organizational-units-for-parent --parent-id "$1" --output text --query 'OrganizationalUnits[][Id]'); do
echo ""
aws organizations describe-organizational-unit --organizational-unit-id "$ou" | jq -r --arg INDENT "$INDENT" '.OrganizationalUnit | "\($INDENT) \(.Name) (\(.Id))"'
get_accounts_recursive "$ou" "$(( $2 + 1 ))"
INDENT=$(printf '=%.0s' $(seq $2))
done
}
aws organizations list-roots | jq -r '.Roots[0] | "\(.Name) (\(.Id))"'
get_accounts_recursive "$1" "1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment