Inventory Existing CloudFormation, Console and Terraform Owners
An ownership register is the first artefact, not the HCL. Every bucket, role and security group already has an owner: a CloudFormation stack, a console habit, a script, another Terraform root, or nobody. Import is a transfer between owners, so the register must name the current one before a resource block is written.
CloudFormation leaves a signature. A stack-managed resource carries AWS-managed tags naming the stack and the logical resource, and the template still declares it. Those tags are the cheapest proof of ownership. While the stack owns the object, a stack update that drops it deletes it by default, so DeletionPolicy: Retain is the documented way to detach it without destruction (DeletionPolicy).
The console is an owner with no record. A resource created by hand has no template, no state address, and often no tags. CloudTrail can show who called the create API, but it cannot say who is expected to maintain the object. Treat console ownership as an explicit decision to adopt or tolerate, never as proof that nobody owns it.
A second root is the dangerous case. If another state already manages the object, importing it creates two declarers. Both plans look clean, and either apply can revert or destroy what the other believes it owns. Transfer through a window where neither root declares the object, then import it into exactly one.
Some objects should stay outside Terraform. Shared networks, account-level guardrails and vendor-managed resources are often better read through a data source than owned by a workload root. Reference them, assert their attributes with preconditions, and leave the owning team's pipeline in charge.
Inventory tools each have a blind spot. Resource Explorer and the Cloud Control API list resource types, but the Resource Groups Tagging API returns only resources that carry at least one tag, so untagged objects are invisible to it. CloudFormation drift detection compares a stack to its template, not to Terraform. No single read proves ownership, so combine the register with one read-only pass per owner type.
Figure 1 shows the decision that follows from that evidence, and Figure 2 places the four owner types on one boundary.
%%{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','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Object exists in the account"] --> B{"What proves the owner?"}
B -->|"aws:cloudformation tags"| C["CloudFormation stack"]
B -->|"state address"| D["An existing Terraform root"]
B -->|"nothing"| E["Console, script or orphan"]
C --> F{"Adopt into this root?"}
F -->|"yes"| G["Add Retain, detach, then import"]
F -->|"no"| H["Read it with a data source"]
D --> I{"Same root and workspace?"}
I -->|"yes"| J["Change it here"]
I -->|"no"| K["Transfer through zero owners"]
E --> L["Name an owner before any HCL"]
G --> M["Register ARN, type, owner and id shape"]
H --> M
J --> M
K --> M
L --> M
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 A,B,F,I primary;
class C,D secondary;
class G,H,J,K,M ok;
class E,L warn;
| Current owner | Evidence to collect | Safe next step |
|---|---|---|
| CloudFormation stack | Stack name, logical ID, deletion policy | Detach with Retain, then import into one root |
| Console or script | Create event, tags, runbook link | Name an owner, then adopt or leave |
| Another Terraform root | State address and workspace | Transfer through zero owners, then import |
| No owner at all | No stack, tag or state record | Register the orphan, then adopt or delete |
Import and Refactor a Bounded Resource Set
Bound the set before you bound the risk. One service, one environment, ten to twenty objects, and nothing whose replacement would lose data. A bounded import is reviewable in one sitting and produces evidence you can attach to a change record; a whole-account import produces a plan nobody can read.
Import support belongs to the resource and the release. Every provider resource page carries an Import section naming the identifier shape. Some resources take a name or ARN, some take a composite, and some have no import implementation. Check the page for the version you pinned, not for the version you remember.
Terraform 1.17 offers three supported entry points. A single import block names the destination address and either a plain id or, since 1.12, a structured identity map, and it is the smallest reviewable change you can commit.
Bulk discovery suits a wider sweep. A query file with list blocks plus the query command can generate importable configuration, including resource identities, without hand-writing each address (bulk import). The older command-line import still works for one object, but leaves nothing behind to review.
A successful import is not a clean plan. Import records the object in state; the next plan compares your HCL with what the API returns. Missing arguments, provider defaults and computed attributes all surface as a diff. The baseline you want is a plan where the imported addresses show no changes except ones you named in advance.
Generated configuration is a draft with secrets. Configuration generation writes literal values, including values that were never meant to be committed. Move them to variables or a secrets lookup, review the file line by line, and never apply a generated file wholesale.
Refactor after the baseline, not during it. Once the plan is stable, change addresses with a moved block and forget objects with a removed block that disables destroy. Both are reviewable in the repository, unlike a manual state edit, and both leave a history the next engineer can follow.
Figure 3 traces the loop and its three failure branches.
%%{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','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Pick 10 to 20 objects from one service"] --> B{"Import documented for this release?"}
B -->|"no"| B1["Keep external or recreate deliberately"]
B -->|"yes"| C["Write resource blocks at final addresses"]
C --> D["Import block with id or identity"]
D --> E["terraform plan"]
E --> F{"Result for the imported set"}
F -->|"replacement"| F1["Stop: configuration does not match"]
F -->|"in-place diff"| F2["Encode the real values, plan again"]
F -->|"no changes"| G["Apply, then remove the import blocks"]
F1 --> C
F2 --> C
G --> H["Refactor with moved and removed blocks"]
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 A,E,F primary;
class B,C,D secondary;
class G,H ok;
class B1,F1 danger;
class F2 warn;
One address per object, decided before import. Importing to a temporary address and moving it later doubles the work. Write the final module path and resource name first, then import there. If the object belongs in a child module, pass the provider explicitly and confirm the module's address appears exactly once in the plan.
Import the dependency, not just the headline resource. A bucket without its versioning, policy and ownership controls is half-owned: the next plan may propose to create those companions, and a create against an existing configuration fails. Import the parent and every companion in the same bounded set, or explicitly record which companions remain external.
Review Provider Upgrades and Tag Normalization
A provider upgrade changes three things at once: the binary, the schema and the plan. The changelog lists features; the upgrade guide lists behaviour changes that can rewrite or replace existing objects. Read the guide for the major version you are entering, then read the release notes between your current pin and the target.
Enter a major version through the last minor of the previous one. The v6 guide requires a clean plan on the newest 5.x release first, with no deprecation warnings. That step is not ceremonial: it is where deprecated arguments surface while the old provider can still read them (v6 upgrade guide).
Some v6 changes are visible in state, not just configuration. Instance user data is no longer hashed and is stored in clear text, which can both change an attribute and leak a value into state. That is a reason to keep secrets out of bootstrap scripts, not a reason to skip the upgrade.
Argument removals fail validation instead of surprising you later. The EIP block lost its vpc argument in favour of domain, and S3 bucket placement moved to bucket_region; both fail validation before any API call. An AMI lookup with most_recent now needs an owner or a filter.
Nullable booleans became strict. The v6 guide lists resources whose boolean arguments now accept only true, false or an empty string, so a configuration using 0 or 1 fails validation rather than silently coercing. That is a plan-time error you can find before the apply by running the upgrade on a branch.
Review the schema diff, not only the plan diff. After terraform init -upgrade, dump the provider schema before and after and diff the attributes your configuration uses. A removed argument is a compile-time error, a changed default is a silent plan diff, and a changed state schema is handled by the provider's upgrader on first read.
Sort the plan into four buckets. Refresh noise re-reads computed values. Normalization rewrites a representation without changing behaviour. Address changes belong to moved blocks. Replacement is the only bucket that can cause an outage, and its reason matters more than its count.
Tags are where upgrades and imports collide. Provider default tags merge into the computed tags_all, and a resource-level tag with the same key wins; the autoscaling group is the documented exception that does not receive them. An imported object often has no tags, so the first plan proposes the whole default set. Review that once as normalization, and do not suppress it with a broad ignore rule.
Normalization needs a policy, not a shrug. The provider's ignore-tags setting suppresses differences for named keys or prefixes, which is right for a scanner tag and wrong for an ownership tag. Use it with a written reason, and never to silence a tag that identifies the owner.
Tag policy enforcement is available in the 6.x provider. Setting tag_policy_compliance to error or warning makes the provider check creates and tag modifications, and the caller needs the tag-policy read permission (tag policy compliance).
| Change in 6.x | What the plan shows | Review action |
|---|---|---|
Instance user_data unhashed | A changed value, stored in clear text | Move secrets out, expect one update |
aws_eip.vpc removed | Invalid argument before any API call | Use domain, confirm no replacement |
S3 bucket region split | Placement looks like it changes | Use bucket_region, check for -/+ |
| Strict nullable booleans | Validation error for 0 or 1 | Use true, false or an empty string |
| Tag policy enforcement | Error or warning on create or tag change | Fix tags, grant the read permission |
Protect Plans and Serialize Writers per Root
A state object has one writer at a time. The backend lock protects one state, not the account, so it stops two applies of the same root from interleaving and does nothing about two roots that both declare the same IAM role. Ownership prevents the second problem; the lock prevents the first (state locking).
Plan and apply must share their inputs. A saved plan captures the configuration, variables, provider selection and refreshed state at plan time. Applying it later is safe only while that state's serial is unchanged. If another writer moved the state, Terraform rejects the stale plan instead of guessing, and that rejection is a feature rather than an obstacle.
The artifact is the approval unit. Write the plan to a file, render its JSON for policy checks and human review, hash both, and store them encrypted with a short retention. Approvers approve that hash, and the apply job downloads exactly that artifact. A pipeline that re-plans after approval has approved nothing.
Federation replaces stored keys. A CI workload presents a short-lived OIDC token, and the role trust policy restricts the repository, ref or environment that may present it (GitHub OIDC). Plan and apply can use different roles: the plan role reads state and APIs, the apply role writes, and only the protected environment's workflow may assume it.
Serialize by root, and queue rather than cancel. A concurrency group keyed on the root path lets one apply finish before the next starts. Cancelling an apply mid-flight is how partial state happens. For brief contention a lock timeout waits; disabling the lock or force-unlocking to clear a queue is how two writers end up applying at once.
Immutable source closes the last gap. Apply from a commit SHA with the committed lock file, not from a branch head that moved during approval. The plan artifact records that SHA, so the evidence links a reviewed diff to the exact code and provider binary that produced it.
Figure 4 shows the gates in order, and Figure 5 contrasts the same pipeline with and without them.
%%{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','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Reviewed commit and lock file"] --> B["Plan with the read role"]
B --> C["Save plan, JSON and hash"]
C --> D{"Policy and approval pass?"}
D -->|"no"| D1["Stop before apply credentials"]
D -->|"yes"| E["Queue per root, acquire lock"]
E --> F{"Lock acquired?"}
F -->|"no"| F1["Wait or fail, never force-unlock"]
F -->|"yes"| G["Apply the exact saved plan"]
G --> H{"Apply finished?"}
H -->|"no"| H1["Partial state, reconcile first"]
H -->|"yes"| I["Release lock, publish evidence"]
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 A,C,G primary;
class B,E secondary;
class F,I ok;
class D1,F1,H1 danger;
class D,H warn;
Reconcile a Partial Apply and Audit Cleanup
A partial apply is a normal failure, not a corrupted state. Terraform walks the graph and stops at the first error. Resources completed before the failure are recorded; the failing resource may be absent, or present and marked tainted if it was created but could not be finalised. The exit code is non-zero, and that plan can no longer be resumed.
Never re-apply the old plan file. That plan described a graph that no longer matches reality. Run a fresh plan, read what it proposes for the addresses that did land, and treat anything it wants to create that already exists as an import candidate.
Reconcile in three passes. First, list state to see which addresses are recorded. Second, refresh to learn what the APIs actually hold, including objects created outside the run. Third, decide per address: keep and import, forget with a removed block, or replace deliberately. A tainted object is a replace decision, not an import.
Drift and partial failure look similar and are not. Drift is a live object that changed after a successful apply; a partial apply is a graph that stopped. A refresh-only plan shows the first without touching configuration, while the second needs a normal plan and often an import. Using refresh-only to settle a partial apply hides the object that state never recorded.
Read the failure before touching state. An access-denied error means nothing after the last success was written. A timeout may mean the create succeeded and the response was lost, which is the import case. A provisioner failure after creation is the taint case. The error text and the resource's API state decide, not the plan summary.
Audit cleanup is part of the change. Confirm the final plan is empty, the objects you meant to keep still have their original identifiers, the ones you meant to remove are gone, and the data you were required to retain still exists. Then remove lab state, roles and artifacts, and close the record with the plan hash and the final no-change evidence.
Reconcile a Partial Apply and Audit Cleanup
Status: design-only. No AWS account was touched for this article, and no command below was executed here. The sequence is written for a disposable sandbox account; treat every identifier as a placeholder.
Prerequisites. Terraform CLI 1.17.1, hashicorp/aws 6.72.0, an AWS CLI v2 profile for the sandbox, and one IAM role whose policy you can edit between steps. No stored access key is needed.
Minimal setup. One root with a versioned S3 bucket, its versioning resource and one standard SSM parameter, all tagged through provider defaults. Set force_destroy = true on the bucket so cleanup cannot stall, and make the parameter depend on the versioning resource so the failure has a deterministic predecessor.
- Apply with full permissions and confirm the next plan is empty.
- Edit the role to deny the parameter write while leaving S3 and SSM reads intact.
- Change the parameter value and apply. The bucket updates land, then the parameter fails.
- Run
terraform state listand a fresh plan, and record which addresses exist. - Restore the permission, apply the new plan, and confirm the plan is empty again.
- Delete the parameter in the console, plan to see the drift, then apply the recreation.
- Destroy, then verify the bucket and parameter are gone.
| Address after the failure | State | Correct next action |
|---|---|---|
| Bucket and versioning | Recorded | Leave them, fix the failing resource |
| SSM parameter | Absent | Re-apply once the write is allowed |
| Parameter deleted later | Recorded, then missing | Plan recreates it from configuration |
Expected observation. Step 3 leaves a non-zero exit, a bucket that exists, and a parameter that does not. Step 4 shows the bucket addresses in state and the parameter only in configuration. After step 5 the plan is empty, and after step 6 it proposes exactly one create.
Failure check. If the plan after step 3 wants to create the bucket, state was never written for a resource that exists; import it rather than applying a duplicate. If the parameter appears as tainted, the create succeeded and a later step failed; replace it deliberately. If the final plan is not empty, read the remaining diff before destroying anything.
Cost and cleanup. One bucket with a few versions and one standard parameter cost pennies for the session. Run destroy, confirm both objects are gone, delete the local state and plan artifacts, and revert the temporary IAM policy.