# S3: storage for everything

Buckets and objects, storage classes, bucket policies, versioning and lifecycle rules that keep the bill small.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 6. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/06-s3

## What you will learn

- Explain how S3 buckets, objects and prefixes fit together.
- Choose a storage class and lifecycle rule for a real workload.
- Keep a bucket private with Block Public Access and encryption enabled.
- Use versioning to recover from an accidental overwrite.
- Describe when static hosting and cross-Region replication make sense.

## Buckets and objects

Before object storage, a team often attached disks to servers and copied files between them. That tied data to
machine capacity and made sharing or replacing servers harder. Amazon S3 stores objects behind an API instead:
applications put and retrieve files from buckets without managing a disk filesystem.

An **object** is data plus metadata addressed by a key. A **bucket** is its container and has a globally unique
name within S3's namespace. Each bucket is created in one AWS Region. A key such as
`logs/2026/10/access.log` looks like a path, but S3 has a flat key namespace; slashes are prefixes that the
console presents like folders. The lesson creates a private practice bucket, uploads files and inspects the
object list. You'll then compare storage, protection and access options before cleaning up every version.

> **Figure.** Amazon S3 bucket list with the devops academy practice bucket selected in the Mumbai Region
>
> The bucket list shows the bucket name and its Region. (1) This practice bucket is in ap-south-1, Mumbai.

> **Figure.** Amazon S3 Create bucket form showing the Mumbai Region and a bucket name
>
> (1) Keep the bucket in the Region where the workload runs. (2) Choose a globally unique bucket name.

> **Figure.** Amazon S3 Create bucket form with ACLs disabled
>
> (1) Leave Object Ownership on ACLs disabled so bucket policies and IAM control access.

> **Figure.** Amazon S3 Create bucket form with all Block Public Access settings enabled
>
> (1) Enable Block all public access. (2) Confirm all four public-access guard rails are enabled.

> **Figure.** Amazon S3 Create bucket form showing the Bucket Versioning controls
>
> (1) Enable Bucket Versioning before the first upload when recovery from overwrites matters.

> **Figure.** Amazon S3 Create bucket form with SSE-S3 selected for default encryption
>
> (1) Select server-side encryption with Amazon S3 managed keys, also called SSE-S3.

> **Figure.** Amazon S3 Create bucket form with the final Create bucket button
>
> (1) Review the settings, then submit the form with Create bucket.

The first checks I run after creating a bucket are simple:

```sh
$ aws s3api get-bucket-location --bucket $BUCKET --query LocationConstraint --output text
ap-south-1
$ aws s3api list-objects-v2 --bucket $BUCKET --query 'Contents[].{Key:Key,Size:Size,StorageClass:StorageClass}' --output table
-----------------------------------------------
|                ListObjectsV2                |
+--------------------+-------+----------------+
|         Key        | Size  | StorageClass   |
+--------------------+-------+----------------+
|  docs/readme.txt   |  12   |  STANDARD      |
|  logs/demo.log     |  12   |  STANDARD      |
|  tmp/to-expire.txt |  12   |  STANDARD      |
+--------------------+-------+----------------+
```

The object key is the important part. Prefixes such as `docs/`, `logs/` and `tmp/` make a large bucket easier to browse and make lifecycle rules easier to target.

> **Figure.** Amazon S3 Objects tab showing docs, logs and tmp prefixes in the practice bucket
>
> S3 presents prefixes like folders. (1) Documentation objects. (2) Log objects. (3) Temporary objects.

## Storage classes

Before storage classes, teams often kept every object in one default tier, even when old archives were rarely
read and recent artifacts were accessed constantly. That made costs hard to match to actual use. An S3 storage
class keeps the same object API but changes the storage, minimum-duration and retrieval-cost trade-offs.

Choose by asking how often the object is read, how quickly it must be available, and how long it must remain
stored. Standard is the normal choice for frequently accessed data. Infrequent-access classes can lower storage
costs but charge for retrieval and may have minimum storage periods. Glacier classes are archival options;
some require a restore request and wait before the object can be read. Intelligent-Tiering monitors access and
moves eligible objects between tiers, with monitoring charges and retrieval characteristics to account for.

| Class                   | Use it when                             | Watch out for                                  |
| ----------------------- | --------------------------------------- | ---------------------------------------------- |
| **Standard**            | The application reads the object often  | The normal storage price applies               |
| **Standard-IA**         | The object is important but rarely read | Retrieval charges and a minimum storage period |
| **Intelligent-Tiering** | Access patterns are not predictable     | Small monitoring charges apply                 |
| **Glacier classes**     | The object is an archive                | Retrieval can take time and costs extra        |

Do not choose Glacier because the name sounds cheap. Start with how often the application reads the object, how quickly it must come back and how long it must stay there. The right answer is often Standard for active artifacts and a lifecycle transition for older ones.

Use a lifecycle rule when the age of an object is a reliable proxy for access frequency. Keep actively used
artifacts in Standard, and move or expire old data only after confirming retention requirements. A common
mistake is comparing only the per-GB storage price: requests, retrieval, minimum duration and restore time can
make a cheaper class a worse fit.

> **Video.** [Amazon S3 Storage Classes: Optimized storage for your workload needs](https://www.youtube.com/watch?v=w5ocEIDR5WE) (Amazon Web Services)

## Lifecycle rules

An S3 lifecycle rule is a scheduled policy for objects. It can transition objects to a colder class or expire them after a period. Filter by prefix or object tags so a cleanup rule does not remove production data by accident.

This rule expires only objects under `tmp/` after one day:

```sh
$ aws s3api put-bucket-lifecycle-configuration \
    --bucket $BUCKET \
    --lifecycle-configuration '{"Rules":[{"ID":"ExpireTemporaryObjects","Status":"Enabled","Filter":{"Prefix":"tmp/"},"Expiration":{"Days":1}}]}'
$ aws s3api get-bucket-lifecycle-configuration \
    --bucket $BUCKET \
    --query 'Rules[].{ID:ID,Status:Status,Prefix:Filter.Prefix,Days:Expiration.Days}' --output table
---------------------------------------------------------
|            GetBucketLifecycleConfiguration            |
+------+--------------------------+---------+-----------+
| Days |           ID             | Prefix  |  Status   |
+------+--------------------------+---------+-----------+
|  1   |  ExpireTemporaryObjects  |  tmp/   |  Enabled  |
+------+--------------------------+---------+-----------+
```

Lifecycle jobs do not run immediately when you save the rule. Treat the rule as automation that will run later, and verify the scope before you enable it.

> **Figure.** Amazon S3 Management tab showing an enabled lifecycle rule for temporary objects
>
> (1) Lifecycle rules run once a day. (2) ExpireTemporaryObjects is enabled and filtered to the tmp prefix.

> **Figure.** A timeline for one object, for example a log file. Day 0 it is uploaded to S3 Standard: highest storage price, no retrieval fee, read often. After 30 days a lifecycle rule moves it to Standard-IA, infrequent access: cheaper to store, with a fee per GB read and a 30-day minimum. After 90 days it moves to Glacier Flexible Retrieval: much cheaper, but reading it means a restore that takes minutes to hours. After 365 days the rule expires the object, deleting it. Storage gets cheaper to the right, reading gets slower and costlier.
>
> A lifecycle rule moves an object to cheaper classes as it ages, then deletes it.

## Versioning

Versioning protects against accidental overwrites and deletes. Each write gets a version ID. A normal delete adds a delete marker instead of immediately destroying the previous version.

```sh
$ aws s3api put-bucket-versioning \
    --bucket $BUCKET \
    --versioning-configuration Status=Enabled
$ aws s3api get-bucket-versioning \
    --bucket $BUCKET
{
    "Status": "Enabled"
}
```

Versioning is not a backup strategy by itself. Old versions still consume storage, and someone with permission to delete versions can remove the recovery point. Pair it with lifecycle rules, restricted delete permissions and, for important data, a separate backup or replication design.

> **Figure.** Amazon S3 Properties tab showing Bucket Versioning enabled for the practice bucket
>
> The Properties tab shows versioning enabled. It keeps multiple variants of an object in the same bucket.

> **Video.** [Amazon S3 Data Protection Overview - Versioning, Object Lock, & Replication | Amazon Web Services](https://www.youtube.com/watch?v=b18KlhIgmjQ) (Amazon Web Services)

## Access control

Keep a new bucket private. S3 access can come from IAM identity policies, bucket policies, access points or presigned URLs. Start with no public access and grant one narrow use case at a time.

**Block Public Access** is a set of guard rails. It blocks common ways of making a bucket or its objects public. It does not replace IAM; it stops public exposure while your identity and resource policies decide which authenticated callers are allowed.

> **Figure.** Amazon S3 Permissions tab showing Block all public access enabled and no bucket policy
>
> (1) Block all public access is on. (2) There is no bucket policy granting public access.

A **presigned URL** is a temporary link signed by an AWS identity. It is useful when a private application needs to let someone upload or download one object without giving that person AWS credentials. Keep the expiry short and scope the URL to one object and one operation.

For a public static site, do not simply turn off Block Public Access. Put CloudFront in front of the bucket and use Origin Access Control so visitors reach the distribution, not the bucket directly. Static website hosting is a simple S3 feature, but its public endpoint does not provide the same private-origin design.

## Encryption

S3 encrypts new objects by default. SSE-S3 uses keys managed by Amazon S3. SSE-KMS uses a KMS key that you control through a key policy and grants.

- Use **SSE-S3** when you need straightforward server-side encryption with no separate key administration.
- Use **SSE-KMS** when you need key rotation controls, audit events or separate permissions for using the key.

Encryption at rest does not decide who can read the object. You still need IAM and bucket policy controls. It also does not replace TLS while the object is moving between the client and S3.

## Static website hosting

If a site contains only files such as HTML, CSS, JavaScript and images, a web server may be more infrastructure
than it needs. S3 static website hosting serves those objects from a website endpoint without a server to patch.
The website endpoint is HTTP-only and its objects must be publicly readable, so it is not a private-origin
design.

For a production public site, keep the bucket private and put CloudFront in front of it. Origin Access Control
lets CloudFront read the bucket while visitors use HTTPS at the distribution. Use direct S3 website hosting
only when its public-access and HTTP limitations are acceptable, such as a temporary demonstration. A common
mistake is disabling Block Public Access to make a site work without understanding that this exposes bucket
objects directly.

For a production site, use a private bucket behind CloudFront. CloudFront supplies HTTPS, caching and edge delivery. Origin Access Control keeps the bucket private and makes the distribution the only intended reader.

## Replication

When one bucket is the only copy, an accidental deletion or a regional outage can leave a workload without its
objects. S3 Replication asynchronously copies eligible new or existing objects from a source bucket to a
destination bucket. The destination can be in the same Region or another Region, depending on the recovery and
residency requirement.

Replication needs versioning on both buckets, a replication rule that selects objects, and an IAM role S3 can
assume to write to the destination. Existing objects need an explicit replication operation; creating a rule
does not automatically copy every old object unless you request that behavior. Replication is not a backup
against every mistake: deletes or compromised permissions may affect both copies, depending on configuration.

Replication needs versioning on both buckets, an IAM role that S3 can assume and a rule that selects which objects to copy. It is not free: the destination stores another copy and replication creates requests and transfer charges. Design the recovery requirement first, then estimate the cost before enabling it.

Use replication when a second copy must be available in another location or account. For point-in-time recovery,
combine it with protected versions, Object Lock where appropriate, or a separate backup policy. Test that a
replicated object arrives and that the recovery role can read it. A common mistake is assuming replication is
instant or treating a same-account destination as protection from an administrator who can delete both sides.

> **Delete every version before deleting a bucket.** An S3 bucket with versioning is not empty when the current objects disappear. List object versions and delete each version, including delete markers. Then delete the bucket and verify that the command returns Not Found.

> **In production.** Keep Block Public Access on, encrypt by default, use least-privilege bucket policies, turn on versioning for important data, and add lifecycle rules that have been reviewed against real prefixes. Put public websites behind CloudFront instead of exposing the bucket directly.

## Presigned URLs are temporary delegation

An application often needs to let a browser transfer one private object without giving the browser AWS
credentials. A presigned URL is a time-limited signature for a specific S3 operation and object key. The
recipient can use it until it expires, so treat the URL itself as a bearer token: anyone who has it can perform
the signed operation within its limits.

The AWS CLI signs a download URL for the named object. The `--expires-in` value is seconds; the signer must
have permission for the operation, and the URL cannot outlive the credentials that signed it. For uploads,
presign a `PutObject` request with the same key and required headers the client will send.

```sh
$ URL=$(aws s3 presign "s3://$BUCKET/uploads/photo.jpg" --expires-in 600 --region ap-south-1)
$ curl --fail --silent --show-error "$URL" -o photo.jpg
```

Use an S3 presigned URL for one direct upload or download. Use CloudFront signed URLs when access should be
controlled at a CDN edge across many cached requests. Keep expiries short, avoid logging full URLs, and generate
them only after authenticating the intended user. A common mistake is assuming a long-lived presigned URL is
safe to publish; it grants access to whoever receives a copy until expiration or another control blocks it.

## Event notifications start a workflow

An application may need to resize an image, scan an upload or index a new document as soon as it arrives.
Instead of polling the bucket, an S3 event notification can send supported object events to SNS, SQS or
Lambda. The destination starts or queues the next part of the workflow.

Filter on event type, key prefix or suffix to send only relevant objects. SQS stores messages until a worker
processes them, which helps absorb bursts or temporary outages. SNS distributes one notification to multiple
subscribers. Lambda can run a short handler directly. Delivery is designed for at-least-once processing, so a
consumer should tolerate duplicate events and avoid processing its own output objects.

```sh
$ aws s3api get-bucket-notification-configuration --bucket "$BUCKET" --region ap-south-1
{
    "QueueConfigurations": []
}
```

Configure the queue ARN returned by `aws sqs get-queue-attributes`; never paste an invented ARN into a lesson.

Use a queue when work can wait and retry; use a fan-out topic when several independent systems need the same
event. Monitor failed invocations and queue age, and add a dead-letter path where the destination supports it.
A common mistake is writing results back under the same prefix that triggers the event, creating a loop. Use
separate input and output prefixes or an explicit filter.

## Object Lock and multipart upload solve different problems

Two different needs are easy to confuse: preventing deletion and transferring a large file reliably. S3 Object
Lock applies retention or legal holds to object versions in a versioned bucket. Multipart upload splits a large
object into parts that can be sent and retried independently, then combines them when the upload is completed.
Multipart upload improves transfer behavior; it does not make the completed object immutable.

Use Object Lock when a compliance or recovery policy requires protected versions, and choose governance or
compliance mode according to who may shorten retention. Use multipart upload for large objects or unreliable
connections; clients can retry failed parts rather than sending the whole object again. Add a lifecycle rule to
abort incomplete multipart uploads so abandoned parts do not continue consuming storage. A common mistake is
leaving incomplete uploads indefinitely or assuming a multipart transfer provides a backup.

## Mission: A private, recoverable artifact bucket

Create a private S3 bucket in ap-south-1, upload a small artifact twice, verify encryption and versioning, add a lifecycle rule for tmp/ and then remove every object version before deleting the bucket.

- You need: AWS CLI configured with permission to create and remove a temporary S3 bucket
- You'll have: A private bucket with two versions of one object, AES256 encryption, an enabled tmp/ lifecycle rule and a verified cleanup

```sh
$ export AWS_REGION=ap-south-1
$ export BUCKET="devops-academy-$(aws sts get-caller-identity --query Account --output text)-$RANDOM"
$ printf '%s\n' 'artifact version one' > artifact.txt
$ aws s3api create-bucket --bucket "$BUCKET" --region "$AWS_REGION" \
    --create-bucket-configuration LocationConstraint="$AWS_REGION"
$ aws s3api put-public-access-block --bucket "$BUCKET" \
    --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
$ aws s3api put-bucket-encryption --bucket "$BUCKET" \
    --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
$ aws s3api put-bucket-versioning --bucket "$BUCKET" --versioning-configuration Status=Enabled
$ aws s3api put-object --bucket "$BUCKET" --key artifacts/build.txt --body artifact.txt
$ printf '%s\n' 'artifact version two' > artifact.txt
$ aws s3api put-object --bucket "$BUCKET" --key artifacts/build.txt --body artifact.txt
$ aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" \
    --lifecycle-configuration '{"Rules":[{"ID":"ExpireTemporaryObjects","Status":"Enabled","Filter":{"Prefix":"tmp/"},"Expiration":{"Days":1}}]}'
$ aws s3api get-bucket-encryption --bucket "$BUCKET" \
    --query 'ServerSideEncryptionConfiguration.Rules[].ApplyServerSideEncryptionByDefault.SSEAlgorithm' --output text
AES256
$ aws s3api list-object-versions --bucket "$BUCKET" \
    --query 'Versions[].{Key:Key,IsLatest:IsLatest,Size:Size,VersionId:VersionId}' --output table
---------------------------------------------
|            ListObjectVersions             |
+-----------+-----------------------+-------+
| IsLatest |          Key          | Size  |             VersionId              |
+----------+-----------------------+-------+------------------------------------+
|  True    |  artifacts/build.txt  |  21   |  L0d2SEzwFCnMQV0jdfbMJe31cqyvZ9xQ   |
|  False   |  artifacts/build.txt  |  21   |  BYoXEGMp2.ZBa4hjl3R05uMDW.8sI9b0   |
+----------+-----------------------+-------+------------------------------------+
$ aws s3api list-object-versions --bucket "$BUCKET" \
    --query '{Objects: Versions[].{Key:Key,VersionId:VersionId}}' > versions.json
$ aws s3api delete-objects --bucket "$BUCKET" --delete file://versions.json
$ aws s3api list-object-versions --bucket "$BUCKET" \
    --query '{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}' > delete-markers.json
$ aws s3api delete-objects --bucket "$BUCKET" --delete file://delete-markers.json
$ aws s3api delete-bucket --bucket "$BUCKET" --region "$AWS_REGION"
$ aws s3api head-bucket --bucket "$BUCKET" --region "$AWS_REGION"
An error occurred (404) when calling the HeadBucket operation: Not Found
```

The two `delete-objects` calls remove versions and delete markers without requiring you to copy IDs by hand. The second file can contain an empty `Objects` list when no delete markers exist. S3 does not let you delete a non-empty versioned bucket.

## Try it

- Create a private bucket in ap-south-1 and verify its Region.
- Upload an object, replace it, and list both versions.
- Turn on default SSE-S3 encryption and confirm it with the CLI.
- Add a lifecycle rule for objects under the tmp/ prefix.
- Delete every object version before deleting the bucket.

## Quiz

1. A team stores build artifacts in S3 and reads them for 30 days. Which starting storage class fits best?
   - S3 Glacier Deep Archive
   - **S3 Standard** (answer)
   - S3 One Zone-IA
   Why: S3 Standard fits objects that are accessed often. A colder class adds retrieval rules and is better for data that is rarely read.

2. Someone deletes an object from a versioned bucket. What does versioning give you?
   - A new Availability Zone
   - A new IAM user
   - **A recoverable object version or delete marker** (answer)
   Why: Versioning keeps object versions. A normal delete adds a delete marker, so an older version can still be recovered.

3. Which setting should be on for a private bucket by default?
   - **Block Public Access** (answer)
   - Static website hosting
   - A public-read bucket policy
   Why: Block Public Access prevents common ACL and policy mistakes from exposing the bucket.

4. A log prefix should be removed after 90 days. What is the right tool?
   - **An S3 lifecycle rule filtered to the prefix** (answer)
   - A larger EC2 instance
   - A Route 53 health check
   Why: Lifecycle rules apply storage transitions and expiration automatically to objects selected by a prefix or tag.

5. You need to serve a public static site from S3 but keep the bucket private. What is the safer design?
   - Make every object public
   - **Put CloudFront in front and use Origin Access Control** (answer)
   - Store the files in IAM
   Why: CloudFront can serve the site while Origin Access Control lets the bucket accept requests only from that distribution.

## Resources

- [Amazon S3 User Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) (AWS Docs)
- [S3 storage classes](https://aws.amazon.com/s3/storage-classes/) (AWS)
- [S3 lifecycle management](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html) (AWS Docs)
- [S3 versioning](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html) (AWS Docs)
- [Blocking public access to buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html) (AWS Docs)
- [S3 encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) (AWS Docs)
- [S3 and CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DownloadDistS3AndCustomOrigins.html) (AWS Docs)
