Back to Terraform

S3 as Infrastructure: Bucket Ownership, Policies, Encryption and Data Lifecycle

November 6, 2026 Wasil Zafar 24 min read

Provision secure storage settings while keeping object data and destructive retention decisions separately owned

Table of Contents

  1. Separate Bucket Identity from Its Configuration Resources
  2. Trace Bucket Policy, IAM, Public Access and Object Ownership
  3. Choose KMS and Retention Controls for the Actual Data Contract
  4. Assign Object Uploads and Dataset Changes to a Data Workflow
  5. Rehearse Recovery and Non-Empty-Bucket Cleanup

Separate Bucket Identity from Its Configuration Resources

A bucket is one resource; its security posture is many. With Terraform 1.17.1 and provider 6.72.0 the bucket owns the name, region, tags and creation-time switches, while policy, ownership, public access, versioning, encryption and lifecycle each attach through a dedicated resource. That split separates a reviewable storage boundary from one opaque blob of settings.

The old inline arguments still exist, and that is the trap. ACL, policy, versioning, lifecycle and encryption fields survive on the bucket as deprecated arguments. Declaring one beside the dedicated resource gives two owners to one setting: the apply succeeds, and the next plan never settles.

Inline and dedicated is two owners

A deprecated inline argument and its dedicated resource both write one remote setting. The apply succeeds and the plan never settles, because each owner keeps undoing the other. Pick the dedicated resource and remove the inline field in the same change.

Identity is the name, and the name changes only by migration. Renaming a bucket forces a new resource, and the destroy half is blocked while objects exist. Put environment and purpose in the name at creation, then keep human labels in tags, which change for free.

The name can now be omitted, but that is a demo convenience. A bucket without a name gets a generated identifier at apply time, fine for scratch and poor for anything another team must reference.

Region and namespace are creation-time too. The provider separates the global namespace from an account-regional one, and neither moves in place. A regional namespace reduces collision pressure, but it changes who can guess the name; record the choice beside the bucket.

A destroy-time flag is not an object management tool. The force_destroy switch empties the bucket when the bucket is destroyed, and it has no effect until an apply records it in state. Using it as routine cleanup is a misunderstanding that ends in data loss.

The public access block has its own destroy switch. Setting skip_destroy removes the block from state without deleting it, which is useful when a bucket must go while the guardrail stays, and dangerous when the next bucket reuses the name. Choose it deliberately rather than to make a destroy pass.

One root should own each attached setting. If two roots can change the same bucket policy or lifecycle rule, neither owns it. Publish the name and ARN as outputs, and let one root attach the policy resources.

Figure 1 shows the identity at the centre, the attached resources around it, and the failure that only appears after a second apply.

Separate Bucket Identity from Its Configuration Resources
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    N["Bucket identity
name, region, namespace, tags"] --> B["aws_s3_bucket
create, replace, destroy"] B --> C1["aws_s3_bucket_policy
one document per bucket"] B --> C2["ownership controls
ACLs on or off"] B --> C3["public access block
four independent flags"] B --> C4["versioning and Object Lock
recovery and immutability"] B --> C5["encryption configuration
SSE-S3 or SSE-KMS"] B --> C6["lifecycle configuration
one per bucket"] B --> S["Terraform state
names and policy only"] D["Objects, versions, multipart parts
the data plane"] -.->|"never enters state"| S L["Deprecated inline arguments
acl, policy, versioning"] -.->|"declared beside C1 to C6"| F["Failure: perpetual diff
or last writer wins"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class N,B,S primary; class C1,C2,C3,C4,C5,C6 secondary; class D ok; class L warn; class F danger;

Read Figure 1 as an ownership map, not a dependency chart. Each edge is a setting that can be planned and destroyed on its own, and each one is a place where a second root can create a conflict.

Figure 2 separates the three layers a reviewer should be able to name without opening the console.

Bucket identity, attached configuration resources and the data plane The bucket name, region and tags form the identity. Policy, ownership, public access, versioning, encryption and lifecycle attach to that identity as separate resources. Object bytes, versions and multipart parts sit below a state boundary that Terraform never crosses. Identity, configuration, bytes Bucket identity name, region, namespace, tags, object lock at creation Access policy bucket policy, one document ownership controls Exposure guardrails public access block, four flags account-level backstop Recovery controls versioning, Object Lock MFA delete, lifecycle Encryption SSE-S3 or SSE-KMS bucket key, blocked SSE-C Retention expiration and transitions noncurrent version expiry Operational edges logging, notifications, CORS website, replication attaches attaches attaches state boundary: names and policy above, content below Data plane object bytes, versions, delete markers, incomplete multipart parts Renaming the bucket plans a create and a destroy, not an update. The destroy is refused while objects remain, so a rename is a migration. No object bytes, versions or multipart parts are recorded in Terraform state.

Trace Bucket Policy, IAM, Public Access and Object Ownership

A request succeeds only when no policy denies it and at least one allows it. Identity policies attach to roles and users, while a bucket policy attaches to the bucket and names principals. In the same account either can grant, which is why a working role makes a bucket policy look optional.

Across accounts, both sides must agree. The bucket policy must name the foreign principal, and that principal's identity policy must allow the S3 actions. A bucket policy alone produces an error on the caller side that looks like a bucket problem.

Explicit deny is absolute. A deny in either policy overrides every allow, including the account root's own access. That is the mechanism behind TLS-only and encryption-required statements, and it is why a break-glass role is not a way around them.

One bucket policy, replaced wholesale. The attach call replaces the entire document, so two resources managing the same bucket silently overwrite each other. Keep one policy per bucket and compose its statements from a policy document data source.

Object ownership decides whether ACLs exist at all. The enforced mode makes the bucket owner own every object and disables ACL-based access; it is the default for new buckets since 2023. The two ACL-based modes remain for legacy pipelines that still ship canned ACLs.

Switching to enforced ownership does not rewrite history. Existing objects keep the account that wrote them, and because ACLs stop applying, a writer from another account can lose the access it had. Migrate ownership before the switch, not after the support ticket.

Public access block is four independent switches. One blocks public ACLs, one blocks public bucket policies, one ignores existing public ACLs, and one restricts a public policy to the owner's account. Only all four together read as private.

The provider's defaults are not AWS's defaults. Each flag defaults to false in Terraform, while AWS enables all four for new buckets. Declaring the resource and setting two flags can turn the other two off; set all four explicitly.

Put the account-level block underneath the bucket-level one. The account block is a floor that a bucket resource cannot weaken, and it catches buckets created outside Terraform. A bucket-level block that disagrees with it only makes the plan noisy.

Two deny statements carry most of the value. Deny requests where the transport is not TLS, and deny uploads that declare no encryption header when the contract requires one. The second forces clients to name the key explicitly, and it will break any client that relied on default encryption.

KMS is a second authorization system. An S3 allow gets the caller to the object; the key policy and the caller's IAM permissions decide whether the bytes decrypt. A bucket policy cannot grant KMS rights, and a key policy that omits the account cannot be repaired with more S3 actions.

Figure 3 places the gates in evaluation order and keeps the two quiet failures visible.

Five gates between a caller and an S3 object A request passes explicit-deny evaluation, then the identity and bucket policy check, then the public access path, then object ownership and ACLs, then the KMS key policy. Each gate has a different denial message, and KMS failure happens after S3 has already allowed the request. One request, five gates Signed request: principal, action, object key 1. Explicit deny in any policy deny wins over every allow, including the owner AccessDenied no allow can override it 2. Identity policy and bucket policy same account: either may allow, cross-account: both must AccessDenied the error names the caller 3. Public path only: public access block public ACLs and public policies are refused at the edge 403 on the public path the object is never reached 4. Object ownership, then legacy ACLs enforced ownership ignores ACL grants entirely ACL has no effect no error, access is gone 5. KMS key policy and IAM decrypt grant evaluated for SSE-KMS after S3 has allowed the call Object bytes returned to the caller

The gate order explains the confusing errors. A KMS denial arrives after S3 authorized the request, so the S3 policy is not the thing to edit. An ACL that silently stops working is an ownership change, not a bad grant.

Figure 4 works through the same evaluation with the failure branches that produce each message.

Trace Bucket Policy, IAM, Public Access and Object Ownership
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    R["Request: principal, action, key"] --> D{"Explicit deny in
bucket or identity policy?"} D -->|"yes"| F1["Deny wins
owner is not exempt"] D -->|"no"| A{"Same account as
the bucket?"} A -->|"yes"| S{"Bucket policy allows
or identity policy allows?"} A -->|"cross-account"| X{"Bucket policy allows
this principal?"} X -->|"no"| F2["AccessDenied
the bucket never granted"] X -->|"yes"| Y{"Caller identity
policy allows?"} Y -->|"no"| F3["AccessDenied
the caller never granted"] S -->|"no"| F4["AccessDenied
neither side allows"] S -->|"yes"| P{"Anonymous or
public path?"} Y -->|"yes"| P P -->|"yes"| PB{"Public access block
and ownership allow?"} P -->|"no"| K{"SSE-KMS only:
key policy and IAM
allow Decrypt?"} PB -->|"no"| F5["403 on the public path
before the object"] PB -->|"yes"| K K -->|"no"| F6["KMS AccessDenied
S3 already allowed"] K -->|"yes"| OK["Object returned"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class R,D,A,S,X,Y,P,PB,K primary; class OK ok; class F1,F2,F3,F4,F5,F6 danger;

Test the layers separately, or the first failure will hide the rest. Remove one grant at a time and record the exact error: caller denial, public 403, ignored ACL and KMS denial are four different repairs.

Choose KMS and Retention Controls for the Actual Data Contract

Default encryption is already on; the decision is whose key. S3 encrypts new objects with SSE-S3 even when the request says nothing, so "encrypt the bucket" is no longer a design choice. The choice is whether a customer-managed KMS key should gate decryption, appear in audit logs and live as a separately owned resource.

SSE-KMS buys control and adds two failure modes. Every read needs a decrypt grant and every write needs a data-key grant, so a missing key policy entry looks like a storage outage. Bucket keys cut KMS calls by reusing a bucket-level key, at the cost of fewer per-object audit events.

Key deletion is the sharpest edge in the design. A KMS key is scheduled with a 7-to-30-day window, and once deleted the ciphertext is unrecoverable. Give the key a prevent_destroy guard and a window long enough to catch a mistake.

Customer-provided keys are leaving the picture. New buckets now block SSE-C by default, and the encryption resource exposes that as an explicit list of blocked types. A legacy client that still sends SSE-C fails at upload with a bad request rather than a policy error.

Versioning is the recovery control, not a backup. It preserves the previous bytes when an object is overwritten or deleted, and a delete becomes a delete marker rather than a removal. It also multiplies storage: every version is billed until a rule removes it.

Suspension is not a rollback. Versioning can be suspended but never returned to an unversioned state, and existing versions remain. A bucket versioned for a quarter carries that storage until the noncurrent rules catch up.

Lifecycle is one configuration per bucket, made of scoped rules. Each rule needs an ID, a status and a filter; a rule without a filter applies to every object, which is how a temporary cleanup deletes shared content. Give each class its own prefix and rule.

Expiry and noncurrent expiry are different clocks. Expiration applies to the current version and leaves a delete marker in a versioned bucket. Noncurrent expiration removes the superseded versions, so a policy that sets only the first leaves every old copy in place.

Transitions have a floor. S3 does not transition objects smaller than 128 KB by default, and each storage class has a minimum billable duration. A 30-day transition on a 7-day dataset costs more than it saves.

Object Lock is a commitment, not a setting. It requires versioning, can be enabled on an existing bucket, and can never be disabled. Retention applies per object version; COMPLIANCE mode cannot be shortened by anyone, including the root user, while GOVERNANCE mode can be bypassed only with an explicit bypass permission.

Default retention covers new objects only. Setting a default does not retroactively lock what is already in the bucket, so a compliance migration needs a per-object pass rather than a single apply.

MFA delete is real but does not fit routine automation. It requires a one-time code from an MFA device for every permanent version deletion, and only the root account can enable it. Treat it as a manual control, not a pipeline step.

The table is a decision aid, not defaults. Read each row as a question about the data contract.

ControlDecision it settlesChoose it whenConstraint to accept
SSE-S3Whether S3 manages the keyNo per-key audit or tenant isolation requirementDecryption cannot be revoked per tenant
SSE-KMS with a customer keyWho decrypts, and where it is recordedRegulated data, tenant isolation, rotation evidenceKey policy is a second gate, and KMS requests cost money
Bucket keysHow often KMS is calledHigh-volume SSE-KMS reads and writesFewer per-object KMS events for audit
VersioningWhether overwrite and delete are recoverableAccidental deletion is a credible riskEvery version is stored until expired
Lifecycle rulesWhen data expires or changes classThe retention window is knownAsynchronous, and minimum durations apply
Object LockWhether a version can change or disappearRegulation or legal hold requires immutabilityCannot be disabled, and COMPLIANCE cannot be shortened

Three questions settle most of the table. Does the contract name a retention period, does it require proof of who decrypted, and can the application tolerate a delayed delete? A no to all three points at SSE-S3, no versioning and a short lifecycle.

Assign Object Uploads and Dataset Changes to a Data Workflow

State is a control-plane ledger, and object bytes do not belong in it. Terraform records attributes and identifiers rather than content, so a bucket and its policy are cheap while a million keys are not. The boundary is not about file size; it is about who changes the data and how often.

The provider has an object resource, and it is easy to misuse. Each object becomes its own address, so a directory of assets becomes hundreds of plan entries and a content release becomes an infrastructure change. The object resource is reasonable for a handful of reviewed bootstrap files, never for a dataset.

An inline content argument puts bytes in state. Writing an object with literal content serialises it into the state file and every backend copy. If a bootstrap object is unavoidable, use the source-file form and keep it small and non-secret.

Bulk data moves through a sync or an SDK, not an apply. A CLI sync, a copy command or the application's own writer bypasses Terraform and touches no state. Scope those credentials to one bucket and prefix, with no permission to change bucket policy.

A release prefix makes rollback a pointer change. Write each release under an immutable prefix, verify checksums, then flip the manifest that readers use. Rolling back becomes a manifest edit rather than a re-upload.

Deletion is a separate, reviewed operation. A mirror sync with deletion enabled removes destination objects the source no longer has, including objects another team serves. Make deletion opt-in, run it against one prefix, and record the object count before and after.

Multipart uploads leave debris when they fail. Incomplete parts are billed until aborted, and no Terraform resource tracks them. A lifecycle rule that aborts them after a day or two is cheaper than an inventory script.

Object tags are part of the data contract. A lifecycle rule can filter by tag and cost allocation can split storage by tag, but tags written by a sync pipeline are not managed by Terraform. Document which side sets them, or the rule matches nothing.

Credentials are the real boundary. The infrastructure role changes policy, the release role writes under one prefix, and the runtime role reads only what it serves. One role with all three makes every pipeline a potential destroyer.

Figure 5 puts the three cadences beside the single ledger only one of them may write.

Infrastructure, release and runtime paths around one state ledger A merge runs Terraform and writes the state ledger. A release syncs objects into an immutable prefix and updates a manifest pointer. Runtime writers put objects through the application. Only the infrastructure path writes state, and object data never crosses the dashed boundary. Three cadences, one ledger Terraform state: names, identifiers and policy only bucket, ownership mode, public access flags, encryption key ARN versioning status, lifecycle rules, Object Lock retention Infrastructure apply on merge plan, review, apply writes state changes policy and keys Release sync on release immutable prefix checksums first never writes state Runtime writes continuous application credentials one bucket, one prefix never writes state reads and writes state release and runtime paths never cross into state Bucket data plane objects, versions, delete markers, multipart parts, object tags written by the release pipeline and the application, never by Terraform state writes bytes writes bytes Only the infrastructure path writes state, and object data never crosses the boundary.

The boundary is proven by the plan, not by a policy document. If a routine content release produces object addresses in the plan, the pipeline is writing through the wrong layer. If an infrastructure apply changes object bytes, the same mistake runs in reverse.

Rehearse Recovery and Non-Empty-Bucket Cleanup

A storage boundary is proven by four checks, and each fails differently. Encryption must be visible on the object, anonymous access refused, a deleted version recoverable, and destroy refused while data remains. A green apply proves none of them.

Start with the object's own metadata. A head request returns the encryption algorithm and, for SSE-KMS, the key that was used. If the bucket says KMS and the object says AES256, the object predates the configuration or ignored it.

Then try the public path and expect refusal. An unsigned request to the object URL should return an access error, not the bytes. A success or a redirect means a policy, an ACL or a public access block is not doing what the configuration claims.

Recovery is a rehearsal, not a setting. Overwrite an object, delete it, list the versions, then restore the earlier one by copying it forward. The copy is the operation a real recovery uses.

Wait before testing versioning on a new bucket. AWS recommends a pause after enabling versioning before the first writes. A test that writes immediately can produce an object with no version and a false conclusion.

Deletion order matters more than the destroy command. A non-empty bucket cannot be deleted, and a versioned bucket is never empty while delete markers remain. Empty the versions, remove the markers, abort incomplete uploads, then destroy.

The blunt instrument is a destroy-time flag. force_destroy empties the bucket at destroy time and cannot be undone. It suits a disposable test bucket and is unacceptable for a bucket whose contents were not separately verified.

Object Lock changes cleanup from tedious to impossible. A COMPLIANCE-locked version cannot be removed before its retention date, by anyone. A lab bucket must not carry object lock, or it cannot be cleaned up the same day.

Cleanup needs an owner and a record. Record the bucket, object count, version count and approver. A silent destroy is more dangerous than a loud failure, because the failure is the last guardrail.

Lab

Rehearse Recovery and Non-Empty-Bucket Cleanup

Execution status: design-only. These steps were not run against a live account. Use disposable names and keep the output as evidence.

Prerequisites. An AWS account, Terraform 1.17.1 with provider 6.72.0, credentials for S3 and KMS, and a bucket name with a run suffix. Do not reuse a production name or enable Object Lock.

  1. Apply the bucket with ownership enforced, all four public access flags on, versioning enabled and SSE-KMS using a key created for the run. Wait about 15 minutes before the first write.
  2. Upload one small object under a test prefix, then read its metadata and record the encryption algorithm and key.
  3. Request the object without credentials and confirm the public path is refused.
  4. Overwrite the object, delete it, list the versions, then copy the first version forward and confirm the original bytes return.
  5. Apply a lifecycle rule scoped to the test prefix that expires current objects after one day and noncurrent versions after seven. Read the rule back; do not wait for deletion.
  6. Attempt to destroy the bucket while the object and its versions remain. Confirm the API refuses the non-empty bucket.
  7. Empty the test prefix, delete every version and delete marker, abort incomplete multipart uploads, then apply the destroy.
  8. Run a final plan with detailed exit codes and confirm it is empty.

Expected observation. The object reports the KMS key rather than SSE-S3, the unsigned request is refused, and the restored copy matches the checksum. The lifecycle rule is visible but nothing has expired, because evaluation is asynchronous. Destroy fails while any version or marker remains.

Failure checks. An object that reports AES256 usually predates the encryption configuration or came from a client that chose its own algorithm. A public request that succeeds points at a public policy, an ignored ACL or a flag left at false. A destroy that removes objects without complaint means the bucket was already empty.

Cost dimensions. A few small objects and a short-lived KMS key cost cents, but versioning, noncurrent versions and KMS requests grow. Object Lock is free to enable and expensive to regret, because retention outlives the exercise.

Cleanup. Empty the prefix, delete versions and markers, destroy the bucket, then schedule the key for deletion with a window long enough to reverse a mistake. Confirm that no other root references the bucket or the key.

References (checked 6 November 2026): bucket resource, bucket policy, ownership controls, public access block, encryption configuration, lifecycle configuration, Object Lock, object ownership, Object Lock retention, and bucket keys.

Next in the Series

In AWS Data Services: RDS, Aurora, DynamoDB and Recovery Boundaries, we'll explore Choose a database lifecycle and prove what Terraform replacement, backup restore and schema migration can each do.