Sub topic 13
Pagination and waiters
This chapter covers two behaviors that affect almost every script you write against AWS. List calls return results in pages, and many create or update calls return before the resource is ready. It assumes you can already build a command with a service, an operation, and options, and that you can filter output with --query. Both topics build on that knowledge.
Why list calls return pages
Most AWS list and describe operations cap how many items they return in a single API response. The cap depends on the service. For example, s3api list-objects-v2 returns at most 1,000 keys per request. If more items exist, the response includes a continuation token. In S3 it is called NextContinuationToken. Other services call it NextToken, Marker, or something similar.
The AWS CLI hides most of this. By default it paginates for you. It calls the API, reads the token, calls again, and merges the pages into one result. You see one combined output.
That default has a cost. On a bucket with millions of objects, a bare list-objects-v2 makes thousands of requests before it prints anything. The options below control this.
The three pagination options
These options are handled by the CLI itself, not by the service. They work only on operations that support pagination.
| Option | What it controls |
|---|---|
| `--page-size` | How many items the CLI asks for in each API call. |
| `--max-items` | The total number of items the CLI returns. |
| `--starting-token` | The token at which to resume a previous listing. |
| `--no-paginate` | Make a single API call and return only the first page. |
Here is the example from the plan:
aws s3api list-objects-v2 --bucket amzn-s3-demo-bucket --max-items 50 --page-size 10The CLI makes up to five calls of 10 items each. It stops after 50 items and prints them as one result.
Page size versus max items
The two options solve different problems.
--page-sizechanges the number of API calls. A smaller page size means more calls, each returning less data. Use it when a single large page times out, which can happen with slow operations or very large pages.--max-itemschanges how much you get back. Use it to sample a listing or to bound a script.
Neither one is a filter. They count items in the order the service returns them.
Resuming with a token
When --max-items stops the CLI before the end of the data, the output contains a NextToken field. Pass that value to --starting-token to continue.
aws s3api list-objects-v2 \
--bucket amzn-s3-demo-bucket \
--max-items 100 \
--output json > page1.json
TOKEN=$(jq -r '.NextToken // empty' page1.json)
if [ -n "$TOKEN" ]; then
aws s3api list-objects-v2 \
--bucket amzn-s3-demo-bucket \
--max-items 100 \
--starting-token "$TOKEN" \
--output json > page2.json
fiThis NextToken belongs to the CLI. It is not the service's own continuation token. Use it only with --starting-token and the same command, and do not pass it to the API directly.
Turning pagination off
--no-paginate makes one call and returns whatever the service sends. Use it when you want the raw service token, or when you want to be sure the CLI makes only one request. The result is not complete if more pages exist.
A common error: `--query` runs per page
The --query filter is applied by the client after the data arrives. With pagination on, the CLI runs the query once on each page. That can produce surprising output when you use functions that look at the whole list.
Consider counting objects:
aws s3api list-objects-v2 --bucket amzn-s3-demo-bucket --query 'length(Contents)'With a large bucket, this can print one number per page instead of one total. The safer approach is to flatten the items and count them outside the CLI:
aws s3api list-objects-v2 \
--bucket amzn-s3-demo-bucket \
--query 'Contents[].Key' \
--output text | wc -wKeys that contain spaces break wc -w. For a reliable count, use --output json and jq 'length', or use the high-level command aws s3 ls --recursive --summarize.
A related edge case: if a page contains no matching items, Contents can be null. Contents[].Key then returns null for that page. Handle this in your script by filtering empty values.
Which operations paginate
Pagination support differs by operation. Check the help page for the operation. If it lists --page-size, --max-items, and --starting-token, it paginates.
aws ec2 describe-instances helpSome operations return everything in one response, so the options have no effect. Some services also offer their own parameters, for example --max-results and --next-token on certain calls. These are API parameters, not CLI options. If you pass them yourself, you take over pagination from the CLI, and the CLI does not merge the pages.
Note that high-level aws s3 commands such as aws s3 ls and aws s3 sync handle pagination internally and do not accept these options.
Why waiters exist
Many AWS operations are asynchronous. The call succeeds when AWS accepts the request, not when the work is finished. For example, aws ec2 run-instances returns an instance ID while the instance is still pending. If your next command assumes the instance is running, it can fail.
You could poll with a loop and sleep. A waiter does this for you. It is a built-in command that checks a resource's state at a fixed interval and exits when the desired state is reached or a limit is hit.
aws ec2 wait instance-running --instance-ids i-0123456789abcdef0The command prints nothing on success and returns exit code 0. It blocks until the instance is running.
Finding waiters
Waiters live under a service's wait command. List them with help:
aws ec2 wait helpTypical waiters include instance-running, instance-stopped, instance-terminated, and bucket-exists under aws s3api wait. Each waiter has a fixed polling interval and maximum number of attempts, and you cannot change them from the CLI. For EC2 instance-running, the CLI polls every 15 seconds for up to 40 attempts, which is about 10 minutes.
Failure behavior
If the waiter reaches the attempt limit, it exits with code 255 and prints an error such as Max attempts exceeded. Some waiters also stop early when the resource enters a failure state. In a script, check the exit code.
if ! aws ec2 wait instance-running --instance-ids i-0123456789abcdef0; then
echo "Instance did not reach running state" >&2
exit 1
fiIf you run a script with set -e, a failed waiter stops the script on its own.
Waiters wait for one state
A waiter checks a single condition. instance-running does not tell you that the operating system has booted or that status checks have passed. For that, use instance-status-ok.
aws ec2 wait instance-status-ok --instance-ids i-0123456789abcdef0Choose the waiter that matches what your next step needs.
Putting it together
This sequence launches an instance, waits, and then reads its public address. Replace the AMI ID with one valid in your Region.
ID=$(aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type t3.micro \
--query 'Instances[0].InstanceId' \
--output text)
aws ec2 wait instance-running --instance-ids "$ID"
aws ec2 describe-instances \
--instance-ids "$ID" \
--query 'Reservations[0].Instances[0].PublicIpAddress' \
--output textEdge cases to remember
- Waiters make read calls, so the identity you use needs the matching
Describepermission. Without it the waiter fails with an access error, not a timeout. - A waiter for a resource that does not exist can fail at once, or run until the limit, depending on the waiter.
- Pagination and waiters both depend on the Region. A waiter polling the wrong Region will not find your resource. Pass
--regionor confirm your profile's default. - For very long operations, waiters can time out before the resource is ready. Combine a waiter with a retry loop, or poll with your own logic and a longer limit.
Exercise
You run aws s3api list-objects-v2 --bucket amzn-s3-demo-bucket --max-items 100 and the output ends with a NextToken value. How do you get the next 100 items, and what does --page-size 20 change in the same command?
Show answer
Run the same command with --starting-token set to the NextToken value. --page-size 20 makes the CLI fetch the items in API calls of 20 each, so reaching 100 items takes about five calls. It does not change how many items you receive in total.
Exercise
A script runs aws ec2 run-instances, then immediately runs a command that needs the instance to be running, and sometimes fails. What should you add, and how do you detect a timeout?
Show answer
Add aws ec2 wait instance-running --instance-ids "$ID" between the two commands. If the waiter hits its attempt limit it exits with a non-zero code (255), so check the exit status, or use set -e so the script stops.