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

52 lines
1.4 KiB
Python
Raw Normal View History

2022-05-14 11:33:56 +08:00
#!/usr/bin/python3
2022-05-13 23:24:11 +08:00
import boto3
2024-03-08 14:10:09 +08:00
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
2022-05-13 23:24:11 +08:00
children = client.list_organizational_units_for_parent(ParentId=ouid).get('OrganizationalUnits')
if len(children) == 0:
printChildAccounts(ouid, level)
2022-05-13 23:24:11 +08:00
return
else:
if ouid.startswith('r'):
printChildAccounts(ouid, level)
for ou in children:
2024-03-08 14:10:09 +08:00
print('.' * 2 * level, ou.get('Name'), ou.get('Id'))
if ouid.startswith('ou'):
printChildAccounts(ouid, level)
recurseChildren(ou.get('Id'), level + 1)
2024-03-08 14:10:09 +08:00
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:
2024-03-08 14:10:09 +08:00
print('.' * 2 * level, account.get('Name'), account.get('Id'))
return
2022-05-13 23:24:11 +08:00
2024-03-08 14:10:09 +08:00
if __name__ == '__main__':
client = boto3.client('organizations')
response = client.list_roots()
rootId = response['Roots'][0]['Id']
print('Root', rootId, sep=": ")
recurseChildren(rootId, 1)
2022-05-13 23:24:11 +08:00