Inventory Is Not Permission to Manage Everything Found
A query is an inventory, not a mandate. It answers what exists where the credentials can read, in the shape the provider chooses to return. Nothing about a result proves the object is safe to own, unowned, or yours.
Four coordinates bound the question. Account or credential, region or project, one resource type, and an ownership marker such as a tag or name prefix. Miss one and the query silently answers a different question than the one you meant.
The account is a credential, not a label. Terraform reads whatever the provider configuration resolves: explicit arguments, environment variables, shared files, or instance metadata. A query that runs under an unexpected profile can return a perfectly valid inventory of the wrong estate.
The ownership marker is the only part you invent. The provider supplies account, region and type semantics; you supply the tag, prefix, or naming convention that separates your workload from shared platforms. A marker nobody enforces is a hope, not a boundary.
Fatal resources belong outside the scope by construction. Shared networks, identity roles, key material, and data-bearing stores should fail the filter before they reach the candidate list. Deciding to exclude them after they appear is a review step that can be skipped under deadline.
Discovery, draft and adoption are three acts. The query reads. The generated file describes. Only an import block and an apply change state. Collapsing them into one command is how a search becomes an accidental ownership transfer.
The output is a ledger, not a queue. Each candidate needs an address, an identity, an owner, a decision and a reason. A list of names is not approval, and a long list is not progress.
Absence proves nothing. Fewer results can mean fewer objects, a narrower grant, a filter typo, or a limit that stopped the read. Treat the empty space as unknown until you can explain it.
Figure 1 shows the four scope decisions and where an unclassified candidate stops.
%%{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["Account and credential"] --> E{"Four coordinates set?"}
B["Region or project"] --> E
C["One resource type"] --> E
D["Owner tag or prefix"] --> E
E -->|"no"| X["Stop: scope or owner unresolved"]
E -->|"yes"| F["terraform query"]
F --> G["Candidate identities"]
G --> H{"Classify each candidate"}
H -->|"adopt"| I["Reviewed import set"]
H -->|"already owned"| J["Exclusion record"]
H -->|"shared or data-bearing"| J
H -->|"owner unknown"| X
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,C,D,E,H primary;
class F,G secondary;
class I ok;
class J warn;
class X danger;
Figure 2 draws the same decision as nested boundaries. Only the innermost set is eligible, and everything outside it still needs a written reason.
Verify List Resource and Identity Support First
Three version claims must be true at once. The CLI must know the query command, the provider must implement list for that resource type, and the resource must expose an identity Terraform can use for import. Each fails differently.
Terraform language support is not provider support. Resource identities arrived in the language at 1.12, and the query workflow appears in the 1.14 documentation set onward. A pinned provider can still lack a list implementation for a type it has managed for years.
Import support does not imply list support. Importers are older than resource identities, and many types can be imported one at a time without ever being discoverable in bulk. Check the provider's list documentation rather than inferring from the resource docs.
Identity is not always a single id. Some providers identify an object by one string; others need a composite of account, name and region. The generated import block reflects whichever schema the provider declares, and a mismatch surfaces at plan time.
Pin the provider build you will query with. A provider upgrade can change list filters, add identity fields, or alter generated argument names. The query and the import must run against the same constraint, or the draft describes a schema you no longer have.
The failure branches are cheap to test. A missing command is a CLI problem, an unsupported type is a provider problem, and an unreadable scope is a credential problem. None of them are fixed by editing the filter.
Probe the type before writing the real query. A one-block query with no filters and a small limit tells you whether the command, provider and identity path work at all. Add scope only after that probe returns something.
The plugin cache is not evidence. An older binary earlier on the path can satisfy the command name while ignoring newer syntax. Record the exact version used for the inventory, the same way you record a state serial.
Figure 3 separates the three gates and the branch each one takes.
%%{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["Terraform CLI"] --> B{"Query command present?"}
B -->|"no"| B1["Stop: upgrade the CLI"]
B -->|"yes"| C["Pinned provider build"]
C --> D{"List implemented for the type?"}
D -->|"no"| D1["Stop: single import or another tool"]
D -->|"yes"| E{"Identity schema usable?"}
E -->|"no"| E1["Stop: no generated import"]
E -->|"yes"| F["Credential for the scope"]
F --> G{"Read succeeds?"}
G -->|"no"| G1["Stop: wrong account or grant"]
G -->|"yes"| H["Run the bounded query"]
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 B,D,E,G primary;
class A,C,F secondary;
class H ok;
class B1,D1,E1,G1 danger;
The order matters. A newer provider cannot rescue a CLI that has no query command, and a wider credential cannot rescue a type the provider never implemented.
Write a Tfquery File and Review Search Results
The query belongs in a .tfquery.hcl file. List blocks are not ordinary configuration; Terraform finds them only by that extension in the working directory. A list pasted into main.tf does not become a query, however valid it looks.
Start from the provider's documented example. The list block names a type and a label, requires a provider reference, and puts provider-specific constraints inside a nested config block. Only the arguments the provider documents are meaningful there.
The provider argument is the account decision. It selects one provider configuration, including any alias, and therefore one set of credentials and one region. Leaving it implicit is not allowed, and defaulting it by habit is how the wrong account enters the ledger.
Set the limit deliberately. The default is 100, and Terraform stops reading when the count is reached. A result set that equals the limit may be truncated, not complete, so compare the count before you trust the inventory.
The first run is a read. terraform query prints one entry per candidate, tagged with the list block that produced it and the provider's identity for the object. It writes nothing to state and changes nothing remotely.
Treat the console as a draft report. Identities alone answer what exists, not who owns it or what it costs. Turn on full resource data only when the review needs attributes, because it widens both the read and the exposure.
Machine-readable output is for diffing, not for deciding. A JSON run lets you compare two inventories over time. It does not add ownership evidence that the query did not collect.
A second run needs a new file. The generation flag refuses to overwrite, and rerunning with the same path fails. Remove the old artifact or choose a new name, and keep the old one as evidence if it was reviewed.
The widget pairs the bounded query with the commands that run and count it.
Read the result before generating anything. If the count is zero, if the count equals the limit, or if an identity belongs to a class you meant to exclude, stop. The generator will happily describe the mistake.
Figure 4 shows the query boundary and the assumptions that make the result trustworthy.
Generate Configuration into a New Local File
Generation is transcription, not design. The flag reads the query results and writes import and resource blocks that describe the objects as the provider sees them. It does not choose an address scheme, remove computed fields, or decide which values you should own.
The output path must not exist. Terraform writes a new file and refuses to replace one. That is a safety property, not an inconvenience: it prevents a rerun from silently replacing the draft you were reviewing.
The file is written on the workstation even when Terraform is connected to HCP Terraform. Query generation happens locally, so the artifact lands in your working directory regardless of where the state lives. Treat that file as sensitive from the moment it appears.
Addresses are the part you must freeze. Generated names follow provider attributes and can collide, truncate, or change when the generator runs again. Rename them once, before import, and use moved blocks for any later change.
The import block carries the identity; the resource block carries the arguments. Depending on the resource, the identity may be a single id or a map of attributes. Do not copy an identity value into the resource body as though it were an argument.
Computed values should not survive review. Identifiers, timestamps, ARNs, and status fields are returned by the provider and recomputed on every read. Keeping one produces a permanent diff or a schema error, never a stable plan.
Defaults are decisions inherited by accident. A generated value reflects what the object has now, not what a fresh create would choose. Keeping it pins today's behaviour; removing it returns the choice to the provider, which is a different promise.
Dependencies written as literals do not order anything. When two adopted objects reference each other by opaque strings, Terraform cannot build a graph or cascade a replacement. Rewrite internal references and keep external ones as variables or data sources.
Secrets can appear in plaintext. If the provider returns a value, the generated file can contain it, and the file is not state-protected. Read every line before the artifact reaches Git, and delete it once the reviewed blocks are merged.
Merge, then delete the draft. Copy only the blocks you reviewed into their final files, remove the generated file, and run a plan. A leftover duplicate declaration is an error; a leftover unmerged block is a second, unreviewed claim.
Figure 5 follows the artifact from draft to reviewed configuration and the four ways it fails review.
Import Only Reviewed Objects and Converge the Plan
Duplicate ownership is the first check, and Terraform cannot run it for you. Import blocks do not consult other state files. A second root that already records the same identity will accept the import, and both plans will look valid until one applies over the other.
Search every root and every workspace. Run a state list in each candidate root, search the repository for the identity string, and compare the provider's own inventory count with the number of addresses you can account for. HCP Terraform can spot identities held by workspaces it knows, but roots outside that organization still need the manual sweep. Write down what each search covered.
Scope the batch to something a reviewer can read. Ten to twenty objects, one owner, one resource family, and no data-bearing object whose replacement loses information. A larger batch produces approval of size, not of correctness.
Freeze the address before you write the block. The module path and resource name decide where the claim lands, and changing either afterward is a state move. The identity belongs in the import block only after the address is settled.
Read the plan summary, not just the word import. The only acceptable first plan is imports plus zero adds, zero changes and zero destroys. An import beside an update attaches the object and changes it in the same run, which destroys the evidence that the import was correct.
A create for an expected object is a stop signal. It means the address, region, credential or provider build differs from the query. Importing at the wrong address does not fail; it records the right object under the wrong name.
A replacement is not adoption. If the plan shows a destroy-and-create pair, an immutable argument disagrees with the live object. Find the argument before applying anything, even when the diff looks small.
Apply the saved plan, then remove the import blocks. The blocks are a record of intent, not the ownership itself. After removal, a fresh plan should still be empty, which proves the state claim stands on its own.
Prove no duplicates outside Terraform. Count the adopted identities in every root and compare with the provider inventory. Each object should appear once as managed, or once in the exclusion record, never both.
The acceptance test is a clean plan with coordinates. Record the Terraform version, provider version, state serial, plan summary and exit code. A no-change plan without those coordinates is a screenshot, not evidence.
A no-change plan has a narrow meaning. It proves the configuration matches the object at that moment, for the addresses you adopted. It says nothing about the objects you deliberately left unmanaged.
The lab below turns the sequence into a bounded rehearsal.
Adopt a bounded inventory
Status: design-only. Written against Terraform 1.17.1 on 6 November 2026. No cloud account was queried and no object was imported, so the outcomes below are documented behaviour rather than measurements.
Prerequisites. A sandbox account or project, a provider build that implements list for one disposable resource type, a read credential, an empty root with a local or remote backend, and a second root you can search for duplicates. Keep every identity as a placeholder.
- Bound the scope. Write one list block for one type, one region, one owner tag and a limit of 20. Record the four coordinates in the ledger.
- Run the query twice. First with JSON output, then again without it, and compare the counts. If either equals the limit, narrow the filter and rerun.
- Generate a draft. Use a fresh output path, then count import and resource blocks. The two counts must match.
- Review the draft. Freeze addresses, delete computed attributes, decide every default, rewrite internal literals as references, and remove secrets.
- Check duplicates. Search every root's state, the repository and the provider inventory for each identity. Exclude anything already claimed.
- Plan the import. The summary must be imports only. Stop on any add, change or destroy on the same address.
- Apply and converge. Apply the saved plan, remove the import blocks, and plan with detailed exit codes. Expect zero.
- Sweep and record. Count the identities across all roots and the provider inventory. Record versions, plan summaries and the exit code.
| Check | Passing result | Stop signal |
|---|---|---|
| Query count | below the limit and explained | equals the limit |
| Block counts | imports equal resources | one side missing |
| First plan | imports only | update or replace |
| Final plan | exit code 0 | any diff |
Expected observation. A short candidate list, a draft whose addresses you chose rather than accepted, and a final plan with no changes. The duplicate sweep returns exactly one record per adopted identity.
Failure check. If the first plan shows an update, the generated configuration disagrees with the live object. If the final plan shows a create, the state and configuration use different addresses. If the sweep finds an identity twice, one root must release it before either applies.
Cost and cleanup. The query is read-only; the lab bills only for sandbox objects that already exist. Destroy the adopted set through the root, confirm an empty plan, then remove the generated files and the query file. Keep the ledger and plan summaries, not state or secrets.
Query-Time Policy Is a Separate Version-Gated Extension
Policy during search is newer than search itself. Query-time evaluation requires Terraform 1.17.0 or later and a remote or agent workspace with policy features enabled. A local query does not gain policy enforcement by upgrading the CLI alone.
The feature is still beta. The documentation says not to use beta functionality in production, which makes query policy a review aid rather than a control. Plan-time policy remains the enforcement point.
Policy input needs resource data. Identities alone are insufficient, so the list block must request full resources or the run must generate configuration. The flag that selects policies does not itself request that data.
Remote evaluation is where the results appear. HCP Terraform evaluates workspace policy sets and any directories passed on the command line, then reports outcomes per list block. A local run has no equivalent evaluation step.
The result classes need different responses. Passed means the generated configuration satisfied the policy. Failed, Unknown and Error all require reading the diagnostics, and N/A means no policy targeted that type, which is not a pass.
Unknown is common and honest. Missing attributes and incomplete relationships prevent a verdict. A policy that cannot see a required field cannot clear the object, and a green summary that counts Unknown as success is misleading.
Query results do not block an import. Even a mandatory policy failure at query time is informational. The import plan is evaluated again, and that is the gate that can stop an apply.
Do not migrate Sentinel or OPA expectations. Query evaluation uses the Terraform policy framework, not the older engines. A policy set that exists only in one of them will not run here.
Version gates belong in the runbook. Record the CLI version, the workspace execution mode, whether policy evaluation is enabled, and the policy set revision. Without them, a green result cannot be reproduced.
The safe reading is narrow. Query policy tells you which discovered objects would fail a policy if generated as configuration. It does not tell you that adoption is approved, that ownership is clear, or that the import plan is safe.
Sources. Bulk workflow, requirements and generation follow HashiCorp's Import existing resources in bulk; block arguments follow the list block reference; flags follow the terraform query command; version gates and result classes follow Evaluate policy on queried resources.