Search code examples
pythonaws-cloudformationboto3

How to get all cloud formation exports Boto3


I'm confused as how to use Boto3's list_exports method.

response = client.list_exports(
    NextToken='string'
)

NextToken (string) -- A string (provided by the ListExports response output) that identifies the next page of exported output values that you asked to retrieve.

Example response syntax

{
    'Exports': [
        {
            'ExportingStackId': 'string',
            'Name': 'string',
            'Value': 'string'
        },
    ],
    'NextToken': 'string'
}

What hasn't been explicitly stated is 1/ missing NextToken parameter is acceptable and 2/ the method must be called repeatedly until all values have been returned.

def get_all_exports(stack):
    map_ = {}
    client = boto3.client('cloudformation')
    response = client.list_exports()
    next_ = response['NextToken']
    helper(response, map_, stack)

    while next_ != '':
        response = client.list_exports(NextToken=next_)
        helper(response, map_, stack)

    return map_ 


def helper(response, map_, stack):
    for ex in response['Exports']:
        if ['ExportingStackId'] == stack:
            key = ex['Name']
            val = ex['Value'] 
            map_[key] = val  

It works! But this seems like a massive pain. Is there not a simpler approach?


Solution

  • Yes, you can use the tokens as you described, but there are also paginators added to help with these operations. You will find them usually listed separately under the service heading, under "Paginators". It appears there is one for listing exports here. If you do not pass in a config for the paginator, it will page through all of the items.

    To use the paginator, you use get_paginator on the client, like this:

    paginator = client.get_paginator(
                "list_exports"
            )
            for page in paginator.paginate(
                <your code here>
            ):