Home > database >  get list of all sub-accounts from given organization in aws
get list of all sub-accounts from given organization in aws

Time:09-29

I am trying to pull list of all aws accounts for given organization (parent) using boto3 API.

import boto3
import json


client = boto3.client('organizations')
paginator = client.get_paginator('list_accounts_for_parent')

response_iterator = paginator.paginate(
    ParentId='<>',
    PaginationConfig={
        'MaxItems': 123,
        'PageSize': 123,
        'StartingToken': 'string'
    }
)

print(json.dumps(response_iterator))

But getting below error however if I use boto3 to pull EC2 instance, it is working.

Traceback (most recent call last):
  File "/Users/kiran.patil/Documents/OFFICE/WorkingDir/BG_Scripts/AWSLambda/invokeLambda.py", line 17, in <module>
    print(json.dumps(response_iterator))
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type PageIterator is not JSON serializable

Thanks for your help in advance.

CodePudding user response:

You're creating a pag, but you're not actually making any API request with it.

Try something like this:

for page in response_iterator:
    print(page)

Unfortunately, while the API response was originally in json, boto3 cooks up the timestamps into datetime.datetime objects, which json.dumps can't handle anyway:

>>> json.dumps(datetime.datetime(2022,9,28,10,30,59))
Traceback (most recent call last):
... ... ... 
TypeError: Object of type datetime is not JSON serializable

@Marcin offers a good workaround - adding the default=str argument to json.dumps:

>>> json.dumps(datetime.datetime(2022,9,28,10,30,59), default=str)
'"2022-09-28 10:30:59"'
  • Related