By the end you'll know
- When to reach for Python and boto3 instead of the AWS CLI, and when not to
- How boto3 finds your credentials, and why it needed an extra package to use
aws login - Why a single call often returns only part of the answer, and how paginators fix it
- How waiters replace
sleepand guessing - How to read AWS's errors, catch the ones you expect, and keep account details out of what you print
- How retries and tags fit into scripts you can run more than once
Before you start
- You need: the
juniper-ryeprofile from Lesson 4, signed in, Python 3.9 or later, and the Python track up to Talking to APIs, which sets up a virtual environment and installs a package. - The script:
boto3-lab.pyandrequirements.txtfrom the practice folder'slesson-20. Everything it creates is namedjr-lesson20-*and taggedlesson=20, and itsdeletestep removes it. - How the script talks to AWS: this time, only through boto3, AWS's Python library. It's the first lab with no AWS CLI calls in it, apart from
aws loginto sign in. - To see every call the script makes that changes something, put
SHOW=1in front of any step, such asSHOW=1 python boto3-lab.py build. The lesson's "By hand" section has the same lab in a Python shell. - Where you run things: your own machine, labeled (Your machine).
- Every output below is from a real run on November 13, 2026.
A script makes things as fast as it can loop
The lab uploads 1,200 files in about 10 seconds. A bug in a loop that creates instances, volumes or NAT gateways works just as fast, and keeps billing after the script ends. Test new scripts with DryRun=True where the service offers it, tag everything a script creates so you can find it again, and keep the budget alarm from Lesson 2 switched on.
The short version
- boto3 is the AWS CLI's Python twin. Both are built on the same library, botocore, and both read the same profiles and credentials.
- Use the CLI for one-off commands, and boto3 when you need logic: loops, decisions, error handling, or a program that runs on its own.
- Many calls return one page of results. S3 lists at most 1,000 objects a call; a paginator fetches the rest.
- Waiters poll until something is ready, so you don't guess with
sleep. - Errors carry a code. Check the code, not the message, catch only what you expect, and mask the rest before printing.
What this lesson costs
| Part | Cost, in us-east-2 |
|---|---|
| 1,200 S3 uploads | $0.005 per 1,000: $0.006 |
| S3 listing, and deleting | Listing under $0.001; deleting is free |
| A DynamoDB table on demand, with three items | Under $0.001 |
| The EC2 dry run and the tagging API | Free |
| This lesson | About 1 cent a run, from credits |
Why Python, when you have the CLI
Every lab so far has been a bash script calling the AWS CLI, with a few lines of Python only to turn JSON into tables. That works until the script needs to decide things: retry this, skip that, stop if a check fails, count what came back. Bash can do it, but each decision means parsing text, and each error is a line on stderr you have to match by eye.
| AWS CLI | boto3 | |
|---|---|---|
| Is | A command-line program | A Python library, AWS's SDK (software development kit) for Python |
| Built on | botocore | botocore, the same one |
| Results | Text or JSON on screen, filtered with --query | Python dictionaries and lists |
| Errors | A message and an exit code | An exception with a code you can check |
| Pages of results | Fetched for you, usually | Fetched for you only with a paginator |
| Best for | One-off commands, quick checks, short scripts | Logic, loops, error handling, Lambda functions (Lesson 21) |
AWS has SDKs for many languages, including JavaScript, Go, Java and .NET. They share the same ideas: clients, pages, waiters, retries and error codes. Learn them once in Python and they carry over.
Set up, and is it allowed?
(Your machine)
cd ~/Apps/aws-practice/lesson-20
python3 --version
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
aws login --profile juniper-rye
| Command | Does |
|---|---|
python3 --version | Checks Python is 3.9 or later; this run had 3.13.0 |
python3 -m venv .venv | Makes a virtual environment, a private set of packages for this folder |
source .venv/bin/activate | Switches this terminal to it; the prompt starts with (.venv) |
pip install -r requirements.txt | Installs what the file lists: boto3[crt]>=1.41 |
aws login --profile juniper-rye | Signs the profile in, in your browser, as in Lesson 4 |
The install ends:
Successfully installed awscrt-0.38.0 boto3-1.44.2 botocore-1.44.2 jmespath-1.1.0 python-dateutil-2.9.0.post0 s3transfer-0.19.3 six-1.17.0 urllib3-2.8.0
The [crt] matters. It adds awscrt, the AWS Common Runtime, which boto3 needs to refresh an aws login sign-in. boto3 only learned to read aws login at version 1.41, and without the extra package it stops with a message telling you to install it. Profiles that use access keys or IAM Identity Center don't need it.
Then check the fence:
python boto3-lab.py fence
== Your tools
Python 3.13.0, boto3 1.44.2, botocore 1.44.2
== Is this allowed in us-east-2?
S3 allowed
DynamoDB allowed
EC2 (read-only calls) allowed
Resource Groups Tagging API allowed
== What it costs, in us-east-2
S3: 1,200 uploads at $0.005 per 1,000 = $0.006; listing and deleting: under $0.001
DynamoDB on demand: a few writes, under $0.001
the EC2 dry run and the tagging API: free
this lab: about 1 cent, if delete runs the same day
Signing in
python boto3-lab.py hello
== Who boto3 signs in as
account: 111122223333
as: assumed-role/AccountFullAccessRole/<your-session>
== How it found your credentials
profile: juniper-rye, from ~/.aws/config
method: login
region: us-east-2
temporary: yes (a session token means the keys expire)
== The same question, asked two ways
CLI: aws sts get-caller-identity --profile juniper-rye
boto3: boto3.Session(profile_name='juniper-rye').client('sts').get_caller_identity()
boto3 used your aws login sign-in, with no keys in the script. The script masks the account ID, as every lab has; the real one is printed by get_caller_identity, so never paste raw output where others can see it.
Every boto3 program starts the same way, with a session and a client:
import boto3
session = boto3.Session(profile_name="juniper-rye", region_name="us-east-2")
s3 = session.client("s3")
ddb = session.client("dynamodb")
| Object | Is | In the lab |
|---|---|---|
| Session | Holds a profile, credentials and a Region | One, for juniper-rye in us-east-2 |
| Client | One service's API calls, named like the CLI's in snake_case: put-object becomes put_object | S3, DynamoDB, EC2, STS and the tagging API |
| Resource | An older, object-style layer for a few services, like s3.Bucket("name") | Not used. AWS has said it won't add new features to it, so new code uses clients. |
| Config | Settings for a client: Region, retries, timeouts | Standard retries, at most 3 attempts |
When you don't name a profile, boto3 looks for credentials in order, and uses the first it finds:
| Order | Where | Used by |
|---|---|---|
| 1 | Keys passed in the code | Almost nothing; don't |
| 2 | Environment variables like AWS_ACCESS_KEY_ID and AWS_PROFILE | CI/CD (continuous integration and delivery) jobs, containers |
| 3 | The profile in ~/.aws/config and ~/.aws/credentials: aws login, Identity Center, roles, keys | Your machine |
| 4 | The role of the container or instance it runs on | Lambda, ECS, EC2: Lessons 21 and 27 |
The same script runs on your machine with your sign-in, and in Lambda with the function's role, without changing a line, as long as it doesn't hard-code a profile. The lab names its profile so it can't use the wrong account by accident.
Making things, and waiting for them
In the console: S3 > Create bucket, then Upload; DynamoDB > Tables > Create table.
python boto3-lab.py build
== The orders bucket, jr-lesson20-orders-d0382a
== 1,200 order files, uploaded 16 at a time
done in 10.5 seconds
== The stock table, and a waiter until it's ready
status right after create_table: CREATING
status after the waiter: ACTIVE (10.5 seconds)
== What there is
jr-lesson20-orders-d0382a: 1,200 objects
jr-lesson20-stock: sourdough 12, croissant 24, rye 8
The upload runs in 16 threads that share one client:
from concurrent.futures import ThreadPoolExecutor
def put(n):
s3.put_object(Bucket=b, Key="orders/2026-11/%05d.json" % n,
Body=('{"order": %d, "item": "sourdough"}' % n).encode())
with ThreadPoolExecutor(max_workers=16) as pool:
list(pool.map(put, range(1, 1201)))
Clients are safe to share between threads; sessions aren't. Make the session and clients once, then hand the client to the threads. One at a time, 1,200 uploads would take a few minutes.
create_table returns while the table is still CREATING. Writing to it then would fail. A waiter asks every 2 seconds until it's ACTIVE:
ddb.create_table(TableName=TABLE, BillingMode="PAY_PER_REQUEST", ...)
ddb.get_waiter("table_exists").wait(TableName=TABLE, WaiterConfig={"Delay": 2, "MaxAttempts": 60})
It's the Python version of the CLI's aws dynamodb wait table-exists, which Lessons 18 and 19 used. Waiters exist for many slow things: instance_running, db_instance_available, bucket_exists, table_not_exists. If the thing never gets there, the waiter gives up after its last attempt with a WaiterError, instead of hanging forever.
One call isn't the whole answer
python boto3-lab.py pages
== One call to list_objects_v2
objects returned: 1,000
IsTruncated: True
a token for the next page: yes
== The same, with a paginator
objects: 1,200, in 2 calls
== A paginator with a JMESPath search, like the CLI's --query
orders of 36 bytes or more (order 1000 and up): 201, the first is orders/2026-11/01000.json
The bucket holds 1,200 orders, and one call returned 1,000. Nothing failed: IsTruncated: True and a continuation token were the only signs that more existed. A script that forgot to check would count 1,000 orders, or delete 1,000 and leave 200, and never say so. The CLI hides this by fetching every page for you; boto3 doesn't, unless you use a paginator:
total = 0
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=b):
total += page["KeyCount"]
| Call | Returns at most |
|---|---|
S3 list_objects_v2 | 1,000 objects |
DynamoDB scan and query | 1 MB of items |
IAM list_roles | 100 roles |
CloudWatch Logs filter_log_events | 10,000 events, or 1 MB |
The rule is simpler than the table: if a call has a paginator, use it. client.can_paginate("list_objects_v2") tells you whether one exists. A paginator's .search() takes a JMESPath expression, the same JSON query language as the CLI's --query, and runs it over every page; here it picked out the 201 orders numbered 1000 and up, whose files are one byte longer.
Reading errors
python boto3-lab.py errors
== Six calls that fail, and what each error says
1. get_object on a key that isn't there
Code: NoSuchKey
HTTP: 404
Message: The specified key does not exist.
2. head_object on the same key
Code: 404
HTTP: 404
Message: Not Found
3. create_bucket with your own bucket's name
Code: BucketAlreadyOwnedByYou
HTTP: 409
Message: Your previous request to create the named bucket succeeded and you already own it.
4. put_item only if the item is new, for one that isn't
Code: ConditionalCheckFailedException
HTTP: 400
Message: The conditional request failed
5. put_object into Deep Archive, which this account's policy denies
Code: AccessDenied
HTTP: 403
Message: User: (an ARN) is not authorized to perform: s3:PutObject on resource: "(an ARN) with an explicit deny in a service control policy: (a policy in the AWS organiz
6. run_instances with DryRun=True
Code: DryRunOperation
HTTP: 412
Message: Request would have succeeded, but DryRun flag is set.
== Catching one error by name, and letting the rest through
rye is already in stock: left it alone
== Retries
retry mode: standard, at most 3 attempts in all
retries this call needed: 0
Every error from AWS arrives as a ClientError, with the details in e.response["Error"]:
from botocore.exceptions import ClientError
try:
s3.get_object(Bucket=b, Key="orders/2026-11/99999.json")
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchKey":
print("no such order")
else:
raise
| Error | Teaches |
|---|---|
1. NoSuchKey | The code names the problem. Match on it, not on the message, which AWS can reword. |
2. 404 | head_object asks for headers only, so S3 sends no error body, and the code is just the HTTP status. Code that checks for NoSuchKey here never matches. |
3. BucketAlreadyOwnedByYou | Different from BucketAlreadyExists, which means someone else has the name. A script run twice can treat the first as fine. |
4. ConditionalCheckFailedException | Lesson 18's conditional write, seen from Python. It's expected, so it's the one to catch. |
5. AccessDenied | The account's SCP (service control policy) blocks Deep Archive, as Lesson 15 found. The raw message held the account ID, the role, the session and the organization's ID. |
6. DryRunOperation | "Would have succeeded": EC2 checked the permissions and the request, and launched nothing. Free, and the safest way to test a script that creates instances. |
Catch only the errors you expect, and let the rest stop the script. Each client also offers its errors as classes, which reads better than comparing strings:
try:
ddb.put_item(TableName=TABLE, Item=item, ConditionExpression="attribute_not_exists(#i)",
ExpressionAttributeNames={"#i": "item"})
except ddb.exceptions.ConditionalCheckFailedException:
print("rye is already in stock: left it alone")
A bare except Exception: pass would have hidden error 5, and the script would carry on as if the archive copy existed.
Error 5 is why the script masks everything it prints. AWS error messages often include ARNs (Amazon Resource Names), account IDs and session names. That's useful to you and not something to put in logs other people read, in a ticket or in a screenshot. The script's mask() swaps them for placeholders before printing. Its line 5 is also cut short at 160 characters, which hid the end of the message; the version in the practice folder now wraps long messages instead.
Retries
Some errors are worth trying again: throttling, when you call faster than a service allows, and brief errors on AWS's side. botocore retries those for you, waiting a little longer each time. The mode is set per client:
from botocore.config import Config
CONFIG = Config(region_name="us-east-2", retries={"mode": "standard", "max_attempts": 3})
s3 = session.client("s3", config=CONFIG)
| Mode | Does |
|---|---|
legacy | The old default: fewer kinds of errors retried, up to 5 attempts |
standard | The same rules in every AWS SDK, up to 3 attempts in all. The default in current boto3; the script sets it anyway, so older versions behave the same. |
adaptive | Standard, plus slowing itself down when it's being throttled. For scripts that hammer one API. |
response["ResponseMetadata"]["RetryAttempts"] says how many retries a call needed: 0 here. A retry never fixes AccessDenied or NoSuchKey; it's for errors that might go away on their own.
Finding things by tag
python boto3-lab.py inventory
== Everything tagged lesson=20, in us-east-2, found through the Resource Groups Tagging API
dynamodb jr-lesson20-stock owner=juniper-rye, lesson=20
s3 jr-lesson20-orders-d0382a owner=juniper-rye, lesson=20
(the tagging API can take a few minutes to notice new and deleted things)
One API found the bucket and the table, across two services, by tag. The Resource Groups Tagging API covers most services that support tags, so a script can ask "what did Lesson 20 make?" without knowing which services to look in. Lesson 26's unused-resource checker builds on this. It's not instant: something just created or deleted can take a few minutes to appear or disappear, which is why the lab's check step asks S3 and DynamoDB directly.
Seeing every call
SHOW=1 uses boto3's event system: the script registers a function that runs before every call, and prints the ones whose names start with Create, Put, Delete and the like:
def show_call(event_name, **kwargs):
service, op = event_name.split(".")[-2:]
...
session.events.register("before-call.*.*", show_call)
The same hooks can add headers, log timings or block calls, without changing the code that makes them.
Take it down
In the console: the bucket > Empty, then Delete; the table > Actions > Delete table.
python boto3-lab.py delete
== Emptying jr-lesson20-orders-d0382a, up to 1,000 keys per delete_objects call
deleted 1,200 objects in 2 calls
deleted the bucket
== Deleting jr-lesson20-stock
deleted
== Anything left from Lesson 20
nothing: all clear
Deleting has the same limit as listing: delete_objects takes at most 1,000 keys a call, so 1,200 objects took two. A bucket must be empty before it can be deleted, and a waiter confirmed each was gone before the check ran. When you're done for the day, deactivate switches the terminal back out of the virtual environment.
By hand: the same lab in a Python shell
Run python with the virtual environment active, then type these one block at a time. (Your machine) Use a bucket name of your own: bucket names are global, which is why the script adds random letters.
import boto3
from botocore.exceptions import ClientError
session = boto3.Session(profile_name="juniper-rye", region_name="us-east-2")
s3 = session.client("s3")
ddb = session.client("dynamodb")
b = "jr-lesson20-orders-yourname"
# The bucket, tagged, and some orders
s3.create_bucket(Bucket=b, CreateBucketConfiguration={"LocationConstraint": "us-east-2"})
s3.get_waiter("bucket_exists").wait(Bucket=b)
s3.put_bucket_tagging(Bucket=b, Tagging={"TagSet": [{"Key": "lesson", "Value": "20"}]})
for n in range(1, 1201):
s3.put_object(Bucket=b, Key="orders/2026-11/%05d.json" % n, Body=b"{}")
# One call, then every page
r = s3.list_objects_v2(Bucket=b)
r["KeyCount"], r["IsTruncated"]
sum(p["KeyCount"] for p in s3.get_paginator("list_objects_v2").paginate(Bucket=b))
# The table, and a waiter
ddb.create_table(TableName="jr-lesson20-stock", BillingMode="PAY_PER_REQUEST",
AttributeDefinitions=[{"AttributeName": "item", "AttributeType": "S"}],
KeySchema=[{"AttributeName": "item", "KeyType": "HASH"}],
Tags=[{"Key": "lesson", "Value": "20"}])
ddb.get_waiter("table_exists").wait(TableName="jr-lesson20-stock")
ddb.put_item(TableName="jr-lesson20-stock", Item={"item": {"S": "rye"}, "count": {"N": "8"}})
# An error, by code
try:
s3.head_object(Bucket=b, Key="orders/2026-11/99999.json")
except ClientError as e:
print(e.response["Error"]["Code"])
# Everything tagged lesson=20
tag = session.client("resourcegroupstaggingapi")
[r["ResourceARN"].split(":")[-1] for p in tag.get_paginator("get_resources").paginate(
TagFilters=[{"Key": "lesson", "Values": ["20"]}]) for r in p["ResourceTagMappingList"]]
# Taking it down
for p in s3.get_paginator("list_objects_v2").paginate(Bucket=b):
s3.delete_objects(Bucket=b, Delete={"Objects": [{"Key": o["Key"]} for o in p.get("Contents", [])]})
s3.delete_bucket(Bucket=b)
ddb.delete_table(TableName="jr-lesson20-stock")
The uploads in this version run one at a time, so they take a few minutes. The tagging list prints ARNs, which include your account ID: fine on your own screen, not for sharing.
In real systems
- Scripts don't name profiles. They take credentials from the environment, so the same code runs on a laptop, in a pipeline with OIDC (Lesson 31) and in Lambda with a role.
- Every list call goes through a paginator, and every create waits with a waiter before the next step relies on it.
- Errors are caught by code, narrowly, and logged with account details masked or kept out of shared logs.
- Scripts are safe to run twice: they check before creating, treat "already exists" as done, and tag what they make.
- Anything that creates infrastructure people keep is Terraform (Lesson 28). boto3 is for glue: reports, clean-ups, checks, and Lambda functions.
- Versions are pinned in
requirements.txtso a new boto3 release doesn't change a production job overnight.
Spot the problem
Work out what's wrong before you read the explanation.
"The clean-up script says it worked, but the bill keeps growing." A nightly job deletes old order files from a bucket of 50,000. It calls list_objects_v2 once, deletes everything older than 90 days from the result, and logs "done". The bucket keeps growing. What's wrong? One call returns at most 1,000 objects, so each night the job only ever sees the first 1,000 keys, the same ones, and never reaches the rest. The fix: use the list_objects_v2 paginator, and delete in batches of up to 1,000. Then check: does the job's log count every object in the bucket, and does the count drop the next night? For a job like this one, an S3 lifecycle rule (Lesson 15) does it with no code at all.
Keep this
| Remember | Why |
|---|---|
| CLI for one-offs, boto3 for logic | Same botocore underneath, same credentials |
| Clients, not resources | The resource layer gets no new features |
boto3[crt] 1.41 or later for aws login | Older versions, or none of the extra, can't refresh it |
| Paginators for every list | One call returned 1,000 of 1,200, with no error |
Waiters, not sleep | The table was still CREATING when the call returned |
| Match error codes, not messages | And head_object's code is just 404 |
| Catch narrowly, mask what you print | Raw messages carry account IDs and ARNs |
DryRun=True before creating instances | Free, and launches nothing |
Where you are now
You've done from Python what Part 3 did from bash: signed in with the same profile, uploaded 1,200 order files in 10 seconds, seen one call stop at 1,000 of them, waited for a table instead of guessing, and read six errors by their codes, one of them the account's own guardrail. Next, Lesson 21 runs Python inside AWS itself: Lambda, where the code that reacts to a new order needs no server, and boto3 gets its credentials from the function's role.
Check yourself
The bucket held 1,200 objects. What did one list_objects_v2 call return?
Why did boto3 need the [crt] extra in this lab?
Right after create_table, what was the table's status?
Code that checks for NoSuchKey after head_object never matches. Why?
What did run_instances with DryRun=True do?
Which error should a script retry?
Why does the lab's script mask everything it prints?
Key terms
- boto3: AWS's SDK for Python.
- botocore: the library under both boto3 and the AWS CLI.
- SDK (software development kit): a library for calling a service from a programming language.
- Session: holds a profile, credentials and a Region.
- Client: one service's API calls, as Python methods.
- Paginator: fetches every page of a call's results.
- Waiter: polls until something reaches a state, or gives up.
- ClientError: the exception for any error AWS sends back, with a code and a message.
- Dry run: a request that's checked but not carried out.
- Retry mode: how botocore retries errors that might go away on their own: legacy, standard or adaptive.
- Resource Groups Tagging API: finds resources by tag, across most services.
- AWS Common Runtime (CRT): a faster, shared core some AWS SDK features need, here for refreshing
aws login.
Go deeper
- Python track: Talking to APIs, Functions and errors, and Scripts you can trust.
- AWS: the boto3 documentation (opens in a new tab), paginators (opens in a new tab), error handling (opens in a new tab), and retries (opens in a new tab).
- AWS: credentials in boto3 (opens in a new tab), and the Resource Groups Tagging API (opens in a new tab).
- Try: run
build, then write a short script of your own that lists every order file with a paginator and adds up their sizes, and catches onlyNoSuchBucketif the bucket isn't there. Run it once with the bucket, and once afterdelete.