Sub topic 4
Working with S3 from the CLI and an SDK
This chapter assumes you have an AWS account, an IAM identity you can sign in as, and the AWS CLI v2 installed. It also assumes you can read basic Python. You will learn which CLI command family to use for which job, how credentials are found, and how to list, read and delete objects safely from boto3, the AWS SDK for Python.
Two CLI command families
The AWS CLI has two ways to talk to S3.
aws s3is the high-level family. It has file-system-like commands (cp,mv,rm,ls,sync) and handles multipart transfers, retries and parallelism for you.aws s3apiis the low-level family. Each command maps one-to-one to an S3 API operation, such ascreate-bucket,head-objectorput-bucket-versioning.
Use aws s3 for moving data. Use aws s3api for configuration and for anything the high-level commands do not expose, such as reading object metadata or a specific version.
| Task | Typical command |
|---|---|
| Copy a file up or down | `aws s3 cp` |
| Mirror a directory | `aws s3 sync` |
| List keys under a prefix | `aws s3 ls` or `aws s3api list-objects-v2` |
| Read metadata without the body | `aws s3api head-object` |
| Change bucket settings | `aws s3api put-bucket-...` |
How credentials are found
Both the CLI and the SDKs use a credential provider chain. They try sources in a fixed order and use the first one that yields credentials. The exact order differs slightly between tools, but the typical sources are:
- Explicit options, such as
--profile. - Environment variables such as
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKENandAWS_PROFILE. - IAM Identity Center (SSO) or assumed-role profiles in
~/.aws/config. - Long-term keys in
~/.aws/credentials. - Container or instance credentials, such as an ECS task role or an EC2 instance profile.
Before doing anything else, check who you are. Many "S3 problems" are really "wrong identity" problems.
aws sts get-caller-identity
aws configure get regionThe first command prints the account ID and the ARN of the identity making calls. The second prints the default Region, which is the Region the tools will use if you do not pass one.
Creating and securing a bucket from the CLI
Bucket creation uses s3api because it needs a Region-specific setting. Outside us-east-1, you must send a LocationConstraint. The second command turns on all four Block Public Access settings, which is a safe starting point for a new bucket.
aws s3api create-bucket \
--bucket my-example-bucket-123456789012 \
--region eu-west-1 \
--create-bucket-configuration LocationConstraint=eu-west-1
aws s3api put-public-access-block \
--bucket my-example-bucket-123456789012 \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueIf you send LocationConstraint for us-east-1, or omit it for any other Region, the call fails. The error message names the problem, so read it before retrying.
Everyday transfers with `aws s3`
aws s3 cp report.csv s3://my-example-bucket-123456789012/reports/2026/report.csv
aws s3 ls s3://my-example-bucket-123456789012/reports/
aws s3 cp s3://my-example-bucket-123456789012/reports/2026/report.csv ./report-copy.csv
aws s3 rm s3://my-example-bucket-123456789012/reports/2026/report.csvTwo behaviors surprise newcomers:
aws s3 lswith a prefix lists one "level" only. It shows keys directly under the prefix and entries markedPREfor deeper prefixes. Add--recursiveto see everything.- A prefix is part of the key string, not a folder. Running
aws s3 ls s3://bucket/reportswithout the trailing slash matches every key that starts withreports, includingreports-old/.
Syncing and the dry run
aws s3 sync copies only files that are new or changed, comparing size and modified time. Add --dryrun first to see what it would do.
aws s3 sync ./site s3://my-example-bucket-123456789012/site/ --dryrun
aws s3 sync ./site s3://my-example-bucket-123456789012/site/ --delete--delete removes objects in the destination that do not exist in the source. It is the only flag here that can destroy data, so run it with --dryrun first. Without versioning, a deleted object is gone.
Inspecting objects with `aws s3api`
head-object returns an object's metadata without downloading its body. It shows the size, ETag, content type, storage class, encryption and version ID.
aws s3api head-object \
--bucket my-example-bucket-123456789012 \
--key reports/2026/report.csvUse it to check that an upload landed, or to test whether a key exists, at the cost of one small request.
Using boto3
boto3 offers two interfaces. The client (boto3.client("s3")) mirrors the API operations and returns plain dictionaries. The resource interface is object-oriented but is no longer receiving new features, so this tutorial uses the client.
The following example uploads a file, lists the objects under a prefix, and downloads the object.
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
s3.upload_file("report.csv", bucket, "reports/2026/report.csv")
response = s3.list_objects_v2(Bucket=bucket, Prefix="reports/")
for obj in response.get("Contents", []):
print(obj["Key"], obj["Size"])
s3.download_file(bucket, "reports/2026/report.csv", "report-copy.csv")upload_file and download_file are managed transfers. They switch to multipart upload for large files and retry failed parts. A later chapter covers tuning that behavior.
Note response.get("Contents", []). When no keys match, the Contents key is absent from the response, so indexing it directly raises a KeyError.
Pagination
list_objects_v2 returns at most 1,000 keys per call. The example above would silently miss keys in a larger listing. Use a paginator, which follows the continuation tokens for you.
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
paginator = s3.get_paginator("list_objects_v2")
total = 0
for page in paginator.paginate(Bucket=bucket, Prefix="reports/"):
for obj in page.get("Contents", []):
total += obj["Size"]
print("bytes under reports/:", total)To list one level at a time, pass Delimiter="/". Keys that contain the delimiter after the prefix are rolled up into CommonPrefixes entries, which behave like subfolders in a listing.
Handling errors
boto3 raises botocore.exceptions.ClientError for service errors. The error code is in err.response["Error"]["Code"].
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
def object_exists(key):
try:
s3.head_object(Bucket=bucket, Key=key)
return True
except ClientError as err:
code = err.response["Error"]["Code"]
if code in ("404", "NoSuchKey"):
return False
raise
print(object_exists("reports/2026/report.csv"))head_object reports a missing key as code "404", because a HEAD response has no body to carry a name like NoSuchKey. get_object reports NoSuchKey. The function above handles both and re-raises anything else, such as 403.
Deleting objects
import boto3
s3 = boto3.client("s3")
bucket = "my-example-bucket-123456789012"
s3.delete_object(Bucket=bucket, Key="reports/2026/report.csv")
s3.delete_objects(
Bucket=bucket,
Delete={"Objects": [{"Key": "tmp/a.txt"}, {"Key": "tmp/b.txt"}]},
)delete_object succeeds even when the key does not exist, so a success response does not prove anything was removed. delete_objects accepts up to 1,000 keys per call and reports per-key failures in an Errors list in the response, so check that list. On a versioned bucket, a delete without a version ID adds a delete marker rather than erasing data, which a later chapter explains.
Common errors
| Symptom | Likely cause |
|---|---|
| `NoSuchBucket` | Typo in the name, or the bucket was deleted. Bucket names are global. |
| `AccessDenied` or `403` | Wrong identity, missing IAM permission, or a bucket policy deny. Run `aws sts get-caller-identity` first. |
| `PermanentRedirect` or Region errors | The client is calling a different Region than the bucket's. Set `--region` or `AWS_DEFAULT_REGION`. |
| `IllegalLocationConstraintException` | `LocationConstraint` is missing outside `us-east-1`, or does not match `--region`. |
| `ExpiredToken` | Temporary credentials from SSO or an assumed role have expired. Sign in again. |
Exercise
A script uses listobjectsv2 to count the objects under a prefix and always reports exactly 1000, even though the prefix holds far more. What is wrong, and what is the fix?
Show answer
A single listobjectsv2 call returns at most 1,000 keys, so the script counted only the first page. Use s3.getpaginator("listobjects_v2") and iterate over every page from paginate(), summing the length of each page's "Contents" list (using page.get("Contents", []) in case a page is empty).
Exercise
You run aws s3 sync ./data s3://my-example-bucket-123456789012/data/ --delete and want to be sure nothing unexpected is removed. What should you do first, and why is this flag riskier on an unversioned bucket?
Show answer
Run the same command with --dryrun first. It prints each upload and delete that would happen without performing any. On an unversioned bucket, objects removed by --delete are permanently gone, while a versioned bucket would keep them as noncurrent versions behind a delete marker.