code-dumps/aws/aws-org-dump.py

52 lines
1.4 KiB
Python
Raw Normal View History

2024-10-24 23:09:21 +08:00
#!/usr/bin/python3
import boto3
def recurseChildren(ouid: str, level: int) -> None:
"""
Recurse down the AWS organization tree and invoke printChildAccounts once
the bottom has been reached
:param ouid: Parent OUID
:param level: Used internally for printing dots
:return: None
"""
global client
children = client.list_organizational_units_for_parent(ParentId=ouid).get('OrganizationalUnits')
if len(children) == 0:
printChildAccounts(ouid, level)
return
else:
if ouid.startswith('r'):
printChildAccounts(ouid, level)
for ou in children:
print('.' * 2 * level, ou.get('Name'), ou.get('Id'))
if ouid.startswith('ou'):
printChildAccounts(ouid, level)
recurseChildren(ou.get('Id'), level + 1)
def printChildAccounts(ouid: str, level: int) -> None:
"""
Print child account details
:param ouid: Parent OUID
:param level: Used internally for printing dots
:return: None
"""
global client
childAccounts = client.list_accounts_for_parent(ParentId=ouid).get('Accounts')
for account in childAccounts:
print('.' * 2 * level, account.get('Name'), account.get('Id'))
return
if __name__ == '__main__':
client = boto3.client('organizations')
response = client.list_roots()
rootId = response['Roots'][0]['Id']
print('Root', rootId, sep=": ")
recurseChildren(rootId, 1)