2

I was Googling around to understand how boto3 paginator works, and found a solution that potentially doesn't require writing any logic with NextToken and While loops.

Still, I'm not quite sure what I'm getting when I'm using this:

client = boto3.client('ec2', region_name='eu-west-1')
results = (
   client.get_paginator('describe_instances')
   .paginate()
   .build_full_result()
)

print(results)

I got a huge JSON output and I'm not sure whether I got what I wanted, which is basically the output of all of my EC2 instances.

I'm also not sure how to loop over it, I keep getting TypeError: string indices must be integers which didn't happen before when I used something like:

for instance in response_iterator:
    instance = instance['Reservations'][0]
    instance_id = instance['Instances'][0]['InstanceId']
    print(instance_id)

I would love to understand how to use the build_full_result() method.

I saw a post that says that it's not documented yet, pretty recent to now (as of writing this post).

Daniel
  • 621
  • 5
  • 22

1 Answers1

3

Interesting find.. this isn't mentioned anywhere in the latest version of boto3 documentation, however it does appear to properly return all available results.

Below is an example from Lambda that shows how to perform a simple loop through the response.. you can update the last two lines to handle the response syntax from EC2 describe instances.

import boto3

client = boto3.client('lambda')

results = (
   client.get_paginator('list_functions')
   .paginate()
   .build_full_result()
)

for result in results['Functions']:
    print(result['FunctionName'])
Tyler
  • 511
  • 5
  • 10
  • 1
    Thanks, I was missing the correct response syntax, I'm getting the full results now. I am also able to filter by adding the `Filters=[{'Name': 'tag:Key', 'Values': ['valueq]}` inside the `paginate()` function. – Daniel Feb 09 '22 at 08:04