Skip to content

Lesson 17 of 30Modern AWS

The AWS CLI and boto3 for Developers

Use the AWS CLI like a power user and write boto3 code that paginates, retries, handles errors and is tested without touching a real account.

23 min read0/4 questions

A cleanup script deletes "all logs older than 90 days" and the bucket still grows. It turns out the script only ever saw the first 1,000 objects. A nightly export job dies twice a week with ThrottlingException. A teammate's test suite quietly creates real queues in the shared dev account. None of these are exotic bugs; they are what happens when people use the AWS CLI and SDKs as if they were simple function calls. This lesson covers the habits that make your AWS tooling correct: knowing who you are, shaping output, pagination, retries, error handling and testing.

Who am I, and where am I?

Every confusing AWS error should start with two questions: which identity is making this call, and in which Region? The CLI answers both.

the first two commands
aws sts get-caller-identityaws configure list

get-caller-identity needs no permissions and returns the account, the ARN and the user ID of whatever credentials resolved. If it says assumed-role/ReadOnly/ada in the staging account, that explains why your PutObject to the prod bucket failed. aws configure list shows each setting (profile, access key, Region) and where it came from: an environment variable, the config file, or SSO. That "where" column is how you catch a stale AWS_ACCESS_KEY_ID exported in your shell months ago, which outranks the profile you think you are using. The full credential chain is covered in Multiple Accounts, Organizations and SSO.

Every command also takes --profile and --region, or reads AWS_PROFILE and AWS_REGION. In scripts, be explicit rather than relying on whatever the shell happens to have. For local sign-in, aws configure sso with IAM Identity Center is the corporate norm; since late 2025, CLI v2 (2.32 or newer) also has aws login, which turns a console sign-in into short-lived CLI credentials. Either beats a long-lived key in ~/.aws/credentials.

When something is mysterious, --debug prints the resolved credentials provider, the endpoint, every HTTP request and every retry. It is noisy, but it ends arguments.

Shaping output with --query and --output

The CLI returns the API's JSON. Two flags turn that into what you actually want.

  • --output picks json (default), yaml, table for humans, or text (tab-separated, ideal for shell loops).
  • --query filters the response with JMESPath, client side, before printing.
useful --query patterns
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query "Reservations[].Instances[].{id: InstanceId, type: InstanceType, name: Tags[?Key=='Name'] | [0].Value}" --output tableaws ec2 describe-images --owners self --query "sort_by(Images, &CreationDate)[-1].ImageId" --output textaws lambda list-functions --query "length(Functions[?Runtime=='python3.9'])"aws s3api list-objects-v2 --bucket my-logs --prefix 2026/ --query "Contents[].[Key, Size]" --output text

The pieces worth memorizing: [] flattens a list, [?cond] filters, {name: expr} builds an object (a multiselect hash), | [0] pipes and picks the first element, sort_by(list, &field) sorts, and length() counts. Prefer --filters (server side) when the API supports it, then --query to shape the rest: server-side filtering sends less data over the wire.

Quoting differs between shells. Wrapping the whole query in double quotes and using single quotes for string literals inside, as above, works in bash, zsh and PowerShell. JMESPath writes numeric literals in backticks (Size > `1048576`), and backticks inside double quotes mean command substitution in bash, so numeric comparisons need single quotes around the whole query in bash. When a query mysteriously matches nothing, suspect the shell's quoting before the query.

Pagination in the CLI

Most list APIs return results a page at a time. The CLI follows the pagination tokens for you and returns everything, so aws s3api list-objects-v2 on a bucket with 3,500 objects makes four calls and prints all 3,500. The flags change that behavior:

FlagEffect
--page-size 100Smaller pages, more API calls, same total output. Useful when big pages time out.
--max-items 100Print at most 100 items and a NextToken you can pass back.
--starting-token TOKENResume from a NextToken.
--no-paginateMake only the first call. You get the first page and nothing else.

CLI v2 also pipes output through a pager (less on macOS and Linux, more on Windows). In scripts and CI, pass --no-cli-pager or set AWS_PAGER to an empty string, or your job hangs waiting for a keypress that never comes.

For long operations, the CLI has waiters: aws ec2 wait instance-running --instance-ids i-0abc polls until the state is reached or a timeout passes. Use them instead of sleep 60 in deploy scripts.

boto3: clients, resources and sessions

boto3 offers two interfaces.

  • Clients (boto3.client("s3")) map one-to-one to the service API. Method names are the API operations in snake case, responses are plain dicts. Every new feature appears here first.
  • Resources (boto3.resource("s3")) are an object-oriented layer (bucket.objects.all()). They read nicely, but the boto3 team has stated it will not add new features to them, and many newer services never had one. Write new code against clients.

Underneath both sits a session, which holds credentials and configuration. boto3.client(...) uses a hidden default session. Create your own when you need a specific profile or Region, or when assuming a role:

clients.py
import boto3
from botocore.config import Config
 
session = boto3.Session(profile_name="analytics-prod", region_name="eu-west-2")
 
CONFIG = Config(
    retries={"mode": "standard", "total_max_attempts": 5},
    connect_timeout=3,
    read_timeout=10,
    max_pool_connections=20,
)
s3 = session.client("s3", config=CONFIG)

Three rules keep this boring. Create clients once and reuse them: creating a client loads JSON service models and is slow, and in Lambda a client created at module level is reused across warm invocations. Clients are thread safe, so threads can share one; sessions and resources are not, so give each thread its own if you use them. Always set the Region explicitly in code that runs in more than one environment.

Paginators and the 1,000-key bug

list_objects_v2 returns at most 1,000 keys per call. Code that calls it once works perfectly in dev, where the bucket holds 40 objects, and silently processes a fraction of production. The same trap exists in almost every list_* and describe_* call: IAM, EC2, CloudWatch Logs, DynamoDB scans.

Run this simulation of the API to see the difference:

Pythonpages.py
# A fake S3 that behaves like list_objects_v2: at most 1,000 keys per call.KEYS = [f"logs/2026/10/{i:05d}.json" for i in range(2500)] def list_objects_v2(Bucket, Prefix="", ContinuationToken=None, MaxKeys=1000): matching = [k for k in KEYS if k.startswith(Prefix)] start = int(ContinuationToken or 0) page = matching[start:start + MaxKeys] resp = {"Contents": [{"Key": k} for k in page], "KeyCount": len(page), "IsTruncated": start + MaxKeys < len(matching)} if resp["IsTruncated"]: resp["NextContinuationToken"] = str(start + MaxKeys) return resp # The bug: one call, looks fine in dev where there are 40 objects.resp = list_objects_v2(Bucket="logs")print("one call:", len(resp["Contents"]), "keys, truncated =", resp["IsTruncated"]) # What a paginator does for you: follow the token until IsTruncated is False.def paginate(**kwargs): token = None while True: page = list_objects_v2(ContinuationToken=token, **kwargs) yield page if not page["IsTruncated"]: return token = page["NextContinuationToken"] pages = list(paginate(Bucket="logs"))total = sum(len(p.get("Contents", [])) for p in pages)print("paginated:", len(pages), "pages,", total, "keys")
Output
Press Run (⌘ Enter) to see what happens.

In real boto3 you never write that loop yourself. Ask the client for a paginator, which knows each operation's token names:

list_all.py
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket="my-logs", Prefix="2026/"):
    for obj in page.get("Contents", []):   # an empty page has no "Contents" key
        process(obj["Key"])
 
# Or filter across all pages with JMESPath:
big = paginator.paginate(Bucket="my-logs").search("Contents[?Size > `1048576`].Key")

client.can_paginate("list_objects_v2") tells you whether a paginator exists. Note the page.get("Contents", []): an empty prefix returns a page with no Contents key at all, a classic KeyError in production.

Waiters are the polling twin of paginators: s3.get_waiter("bucket_exists").wait(Bucket=name) or ec2.get_waiter("instance_running").wait(InstanceIds=[iid]). They retry a describe call on a fixed delay up to a maximum number of attempts, then raise WaiterError.

Predict the outputPython

A bucket prefix holds 4,321 objects. How many list_objects_v2 calls does a paginator make with the default page size?

import math
print(math.ceil(4321 / 1000))
Need a nudge? Hints walk you through it.

Errors: ClientError and what is inside it

Almost every service error arrives as botocore.exceptions.ClientError. The useful parts live in e.response:

errors.py
from botocore.exceptions import ClientError
 
try:
    obj = s3.get_object(Bucket=bucket, Key=key)
except s3.exceptions.NoSuchKey:
    return None                                   # modeled exception: a ClientError subclass
except ClientError as e:
    code = e.response["Error"]["Code"]            # "AccessDenied", "SlowDown", ...
    status = e.response["ResponseMetadata"]["HTTPStatusCode"]
    request_id = e.response["ResponseMetadata"].get("RequestId")
    log.error("s3 get failed", extra={"code": code, "status": status, "request_id": request_id})
    raise

Modeled exceptions such as s3.exceptions.NoSuchKey or dynamodb.exceptions.ConditionalCheckFailedException hang off the client and are subclasses of ClientError, so put them first. Not every error is modeled, and some surprise people: head_object on a missing key raises a plain ClientError with code "404", not NoSuchKey, because a HEAD response has no body to carry the error name. Always log the request ID; it is what AWS Support asks for.

Some failures are not ClientError at all: NoCredentialsError (nothing in the chain resolved), ParamValidationError (you passed a wrong type, caught before any network call), EndpointConnectionError and ReadTimeoutError (network). Handle them deliberately rather than with a bare except Exception.

Retries, timeouts and idempotency

The SDK retries some errors for you: throttling (ThrottlingException, SlowDown, ProvisionedThroughputExceededException), 5xx responses and transient network failures. How it retries depends on the retry mode:

  • legacy: boto3's default if you configure nothing, with up to 5 total attempts.
  • standard: the cross-SDK behavior, 3 total attempts by default, exponential backoff with jitter, and a retry quota that stops retry storms when a service is unhealthy. Prefer it.
  • adaptive: standard plus client-side rate limiting that slows your own sending after throttles. Useful for a single heavy batch job, still marked experimental.

Set it in code with Config(retries={"mode": "standard", "total_max_attempts": 5}), or with retry_mode and max_attempts in ~/.aws/config. One trap: in the config file and in AWS_MAX_ATTEMPTS, max_attempts counts the first request; inside a Config object, max_attempts counts retries only. total_max_attempts always means total, which is why it is the safer key.

Predict the outputPython

How many HTTP requests can one call make with Config(retries={'mode': 'standard', 'max_attempts': 3}) if every attempt is throttled?

initial_call = 1
retries_from_config_object = 3   # max_attempts in a Config object means retries
print(initial_call + retries_from_config_object)
Need a nudge? Hints walk you through it.

Backoff with jitter matters because without it, a hundred workers throttled at the same instant retry at the same instant and get throttled again. Each worker instead sleeps a random time under an exponential ceiling:

Pythonbackoff.py
import random random.seed(7)BASE, CAP = 1.0, 20.0 # seconds: the ceiling doubles and is capped def full_jitter(attempt): # exponential ceiling, then a random point under it return random.uniform(0, min(CAP, BASE * 2 ** attempt)) def call_with_retries(fail_times, max_attempts=3): waited = 0.0 for attempt in range(max_attempts): if attempt >= fail_times: return f"ok on attempt {attempt + 1}, waited {waited:.2f}s" if attempt + 1 == max_attempts: break delay = full_jitter(attempt) waited += delay print(f" attempt {attempt + 1}: ThrottlingException, sleeping {delay:.2f}s") return f"gave up after {max_attempts} attempts" print(call_with_retries(fail_times=2))print(call_with_retries(fail_times=5))
Output
Press Run (⌘ Enter) to see what happens.

Set timeouts too. botocore's defaults are 60 seconds to connect and 60 seconds to read. Inside an API request with a 10-second budget, a single hung S3 call can eat the whole budget, then retry. Choose connect_timeout and read_timeout from your own latency budget.

Retries raise a correctness question: what if the first attempt succeeded but the response was lost? For reads, nothing bad happens. For creates, you might get two. APIs that create things take an idempotency token (ClientToken on RunInstances, ClientRequestToken on Secrets Manager PutSecretValue). botocore generates one automatically per call and reuses it across its own retries, which protects you there. But if your code catches an error and calls again, that is a new call with a new token, and you can launch two instances. When you retry at the application level, generate the token yourself (a UUID tied to the job) and pass it on every attempt.

One token saves you, a second token double-launches
Your codeboto3EC2 APIrun_instances(...)RunInstances tok-Aretry: RunInstances tok-Ai-111ReadTimeoutError (say all retries timed out)run_instances(...) againRunInstances tok-B

You do not pass a ClientToken, so botocore generates one for this call: tok-A.

1/7
Match the pairs0/5 matched

Match each failure to how it reaches your Python code.

Choose an item, then its match on the other side.

Typing and async

boto3 builds its methods at runtime, so editors and type checkers know nothing about them by default. Install the stub packages (types-boto3 or the older boto3-stubs, with extras per service like types-boto3[s3]) and annotate clients as S3Client. You get autocompletion for parameters and response keys, and mypy or Pyright catches Bucket misspelled as bucket before it reaches production.

boto3 is synchronous. In an async FastAPI app, a blocking boto3 call stalls the event loop. You have two honest options: run the call in a thread (await asyncio.to_thread(s3.get_object, ...) or FastAPI's threadpool), or use aioboto3/aiobotocore, a community async port. Threads are simpler and fine for a handful of calls per request. The async port pays off when one request fans out to dozens of concurrent AWS calls. Do not mix them casually in one code path.

Testing without touching AWS

Unit tests must never reach a real account: they get slow, flaky and expensive, and they leave debris. There are three tools, for three jobs.

  • moto fakes AWS services in memory. Since moto 5, one decorator or context manager, mock_aws, covers every service. Use it when your code does several calls and you care about the resulting state.
  • botocore's Stubber queues exact responses for exact requests on one client. Use it to test error paths (throttling, AccessDenied) that moto does not simulate easily, and to assert precisely which parameters you sent.
  • LocalStack runs a local AWS emulator in Docker for integration tests that span services (a Lambda reading from SQS writing to DynamoDB). Slower, broader, and good in CI.
test_archive.py
import boto3
import pytest
from botocore.stub import Stubber
from moto import mock_aws
 
from app.archive import count_old_logs, read_config
 
@pytest.fixture(autouse=True)
def fake_credentials(monkeypatch):
    # if anything escapes the mock, it fails instead of hitting a real account
    monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing")
    monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing")
    monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-2")
 
@mock_aws
def test_counts_every_page():
    s3 = boto3.client("s3")
    s3.create_bucket(Bucket="logs", CreateBucketConfiguration={"LocationConstraint": "eu-west-2"})
    for i in range(2500):
        s3.put_object(Bucket="logs", Key=f"old/{i}.json", Body=b"{}")
    assert count_old_logs(s3, "logs") == 2500     # fails if the code forgot to paginate
 
def test_missing_config_returns_default():
    s3 = boto3.client("s3")
    with Stubber(s3) as stub:
        stub.add_client_error("get_object", service_error_code="NoSuchKey", http_status_code=404)
        assert read_config(s3) == {}

Notice the design that makes this easy: functions take the client as a parameter instead of creating it inside. That one habit makes boto3 code testable.

Quick check
Your function retries on ThrottlingException and logs the request ID. Which tool tests that path most directly?
Need a nudge? A hint rules out a wrong answer.

The same ideas in TypeScript: SDK v3

Version 2 of the AWS SDK for JavaScript reached end of support in September 2025. Version 3 is modular: you install one package per service and send command objects through a client.

s3.ts
import { S3Client, GetObjectCommand, NoSuchKey, paginateListObjectsV2 } from "@aws-sdk/client-s3";
 
const s3 = new S3Client({ region: "eu-west-2", maxAttempts: 5, retryMode: "standard" });
 
export async function readText(bucket: string, key: string): Promise<string | null> {
  try {
    const res = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
    return (await res.Body?.transformToString()) ?? null;
  } catch (err) {
    if (err instanceof NoSuchKey) return null;
    throw err;
  }
}
 
export async function countKeys(bucket: string): Promise<number> {
  let n = 0;
  for await (const page of paginateListObjectsV2({ client: s3 }, { Bucket: bucket })) {
    n += page.Contents?.length ?? 0;
  }
  return n;
}

Everything from the Python sections carries over: clients created once, paginators (paginate* functions) instead of hand-rolled loops, modeled errors you can test with instanceof, retry mode and attempts on the client, and aws-sdk-client-mock playing the role of Stubber in tests. Because each service is its own package, Lambda bundles stay small.

Key terms
JMESPath
The query language behind --query and paginator .search(): filters, projections, functions like sort_by and length.
paginator
A boto3 helper that follows an operation's continuation tokens and yields every page.
waiter
A helper that polls a describe call until a resource reaches a state, or raises after a maximum number of attempts.
ClientError
botocore's exception for service errors; the code and request ID live in e.response.
retry mode
SDK retry behavior: legacy (boto3 default), standard (recommended) or adaptive (adds client-side rate limiting).
idempotency token
A client-supplied value such as ClientToken that lets AWS recognize a repeated create request and not do it twice.
moto
A Python library that fakes AWS services in memory for unit tests, via the mock_aws decorator.