cd ../blog
#terraform#aws#iac#terraform-query#import

Find What Nobody Wrote Down: Importing Unmanaged AWS Resources with terraform query

Terraform 1.14 added list resources and terraform query. I pointed them at an account full of click-ops instances and buckets, generated the config, imported everything in one apply, and found a trap that silently imports the same instance twice.

Jaba Macharashvili 9 min read

In this post
  1. The lab
  2. Which resources can you query?
  3. Step 1: the query file
  4. Step 2: run the query
  5. Step 3: generate the config
  6. Step 4: the generated config does not plan
  7. Step 5: import, and the trap
  8. Step 6: give things real names
  9. What about the new policy flag?
  10. What I would do on a real account
A radar sweep scans an AWS account full of untracked instances and buckets; each one it finds travels along a dashed line into the Terraform state file

Every AWS account I have ever inherited had the same two layers. The layer in Terraform, and the layer somebody built in the console at 11pm during an incident and never wrote down. The second layer is where the surprises live: the jump host with port 22 open to the world, or the bucket called tmp-exports that turns out to hold the only copy of something.

Getting that layer into Terraform used to be a slog. You listed things with the AWS CLI, wrote import blocks by hand, ran plan -generate-config-out, and repeated the loop for every resource type. Terraform 1.14 folded most of that into the tool itself with list resources and terraform query, and 1.17 (released October 21, 2026) added the option to run policies on what the query finds. I wanted to see how far it gets you on a messy account, so I built one and ran the whole workflow end to end, including the parts that went wrong.

The lab

I ran this against moto, a local AWS mock, so every name and ID in the screenshots is the tool’s real output and nothing from my employer’s account. Against a real account the only difference is the provider block: you delete the endpoints and the fake keys. The commands, the generated files and the trap at the end are identical.

ComponentVersion
Terraform1.17.0
AWS provider6.70.0
moto (Docker, motoserver/moto)latest, October 2026
macOS27.0, Apple Silicon

If you have Terraform from Homebrew’s core tap, check terraform version first. The core formula is frozen at 1.5.7 because of the license change, and nothing below works on it. Grab 1.17 from releases.hashicorp.com or the hashicorp/tap.

The account has a VPC, a subnet, a security group, five EC2 instances and three S3 buckets. I created them with a throwaway Terraform config and then threw its state away, which is as close to click-ops as you can get in a script. Three instances are tagged properly, one has an env tag and no owner, and one called forgotten has only a Name tag.

Which resources can you query?

A list resource is something a provider has to implement, so the first thing to check is what your provider version actually supports. The schema dump tells you:

terraform providers schema -json \
  | jq '.provider_schemas["registry.terraform.io/hashicorp/aws"].list_resource_schemas | keys'

AWS provider 6.70.0 reports 259 of them. The ones most people will care about are all there: aws_instance, aws_vpc, aws_subnet, aws_security_group, aws_s3_bucket, aws_iam_role, aws_lambda_function, aws_db_instance, aws_cloudfront_distribution, aws_wafv2_ip_set, aws_route53_zone. If the type you need is missing, you are back to the old import-block workflow for that one type.

Step 1: the query file

Queries live in files ending in .tfquery.hcl, next to your normal .tf files. Each list block names a resource type, the provider to use, and an optional config block whose contents are provider specific. For AWS the filter blocks are the same ones the EC2 API takes, so anything that works in describe-instances --filters works here.

# discovery.tfquery.hcl

# Every running instance in the region.
list "aws_instance" "running" {
  provider = aws

  config {
    filter {
      name   = "instance-state-name"
      values = ["running"]
    }
  }
}

# Every bucket.
list "aws_s3_bucket" "all" {
  provider = aws
}

The provider itself is configured in providers.tf as usual. A query file can carry its own provider block, and most examples online show it that way, but if your main config already has one for the same provider Terraform stops with Duplicate provider configuration. Pick one place.

Step 2: run the query

terraform init
terraform query

Terminal: terraform query lists three S3 buckets and five running instances, each with an identity of account_id, id and region, and the Name tag as a display name

Each line is the query address, the resource identity (the fields Terraform needs to import it, so for an instance that is account_id, id and region), and a display name the provider picks, which for EC2 is the Name tag. The whole query against the mock took about three seconds. I have not timed it on a real account, but it makes the same describe calls the CLI would, so expect seconds rather than minutes.

That screenshot is from my first version of the query file, which had a third list block for tag:env = prod. Keep that in mind, it matters later.

For CI you want -json, which streams one JSON object per event. This pulls out the discovered resources:

terraform query -json \
  | jq -c 'select(.type=="list_resource_found") | .list_resource_found | {address, display_name, identity}'

Step 3: generate the config

The discovery output is nice to look at, but the point is this flag:

terraform query -generate-config-out=generated.tf

Terminal: terraform query with -generate-config-out writes generated.tf containing 11 resources in 711 lines

For every discovered resource Terraform reads its full state from the provider and writes a resource block with every attribute filled in, plus an import block that uses the identity from the query. Instances come out at around 70 lines each. The import blocks look like this:

import {
  to       = aws_instance.running_3
  provider = aws
  identity = {
    account_id = "123456789012"
    id         = "i-f5d903a3a80bd2de8"
    region     = "eu-central-1"
  }
}

That is identity-based import, which arrived in 1.12. It is why the whole thing works across resource types without you knowing each type’s import ID format.

One warning from the first run: the S3 list did a full read of each bucket, and that includes an S3 Control ListTagsForResource call. My provider block pointed s3 at the mock but not s3control, so that call went to the real AWS and came back 403. On a real account this is a reminder that the IAM identity running the query needs read permissions for everything the provider touches during a full read, which is more than ec2:Describe*.

Step 4: the generated config does not plan

terraform plan

Terminal: terraform plan fails with Conflicting configuration arguments: primary_network_interface conflicts with associate_public_ip_address, and ipv6_address_count conflicts with ipv6_addresses, 24 errors across 8 instances

The generator writes every attribute the provider returned, and for aws_instance three of them are mutually exclusive in the schema. Every instance gets the same three errors. This is the same behaviour as the older plan -generate-config-out, so if you have used that you have seen it before.

It also writes a lot of noise you do not want to keep: tags_all, a timeouts block full of nulls, and a line for every optional argument set to null. I cleaned it with a short Python script, because sed and multi-line blocks do not get along:

import re
s = open("generated.tf").read()
s = re.sub(r"\n  ipv6_address_count\s*=.*", "", s)
s = re.sub(r"\n  ipv6_addresses\s*=.*", "", s)
s = re.sub(r"\n  primary_network_interface \{\n.*?\n  \}", "", s, flags=re.S)
s = re.sub(r"\n  timeouts \{\n(?:.*?= null\n)+  \}", "", s)
s = re.sub(r"\n  \w+\s*= null", "", s)
s = re.sub(r"\n  tags_all = \{.*?\n  \}", "", s, flags=re.S)
open("generated.tf", "w").write(s)

711 lines became 535, and the plan went through.

Step 5: import, and the trap

Terminal: terraform plan now shows 11 resources to import, 0 to add, 0 to change, 0 to destroy

Eleven resources to import, zero to change. That second number is the one to watch: if the generated config did not match reality you would see updates here, and an apply would change real infrastructure.

terraform apply

Terminal: terraform apply runs the imports and ends with Apply complete, 11 imported

Eleven imported. Except the account has eight things in it: five instances and three buckets.

Remember the extra list block for tag:env = prod? It matched three instances that the running block had already matched. Terraform generated a resource block for each hit in each list, so those three instances got two resource blocks each, prod_0 and running_1 and so on, and two import blocks. Plan did not complain. Apply did not complain. It imported the same instance into two state addresses, and terraform state list happily shows eleven entries.

I wrote a few lines to find them, because reading instance IDs across eleven blocks by eye is how you miss one:

# dupcheck.py: pipe `terraform show -json` into this
import json, sys, collections
d = json.load(sys.stdin)
seen = collections.defaultdict(list)
for r in d["values"]["root_module"]["resources"]:
    seen[(r["type"], r["values"].get("id"))].append(r["address"])
for (t, i), addrs in sorted(seen.items()):
    flag = "   <-- imported twice" if len(addrs) > 1 else ""
    print(f"{i:<22} {', '.join(addrs)}{flag}")

Terminal: terraform state list counts 11 entries, and dupcheck.py shows three instance IDs that each appear at two state addresses, marked imported twice

Why this is worse than it looks: both addresses point at one real instance. If someone later removes aws_instance.prod_0 from the config because it looks like a leftover, the next apply terminates the instance that aws_instance.running_1 also manages. I would rather find that in a mock.

The fix is two steps. Remove the duplicate addresses from state, which does not touch the instances:

terraform state rm aws_instance.prod_0 aws_instance.prod_1 aws_instance.prod_2

Terminal: terraform state rm removes three duplicate addresses and reports three resource instances removed

Then delete those blocks from generated.tf, and delete the overlapping list block from the query file so it cannot happen again. The rule I took away: one list block per set of real things. If you want both “all running” and “only prod”, filter the output of one query instead of writing two.

Step 6: give things real names

The generator names resources after the list block plus a counter: running_0, all_2. That is fine for a day and useless in six months. Since the resources are already in state, renaming is a moved block, not another import:

moved {
  from = aws_instance.running_0
  to   = aws_instance.forgotten
}

moved {
  from = aws_s3_bucket.all_0
  to   = aws_s3_bucket.tmp_exports
}

I also deleted the import blocks at this point, since they have done their job, and renamed generated.tf to imported.tf.

Terminal: terraform plan reports each resource has moved to its new address, with 0 to add, 0 to change, 0 to destroy

One apply records the moves, and from then on the plan is empty:

Terminal: terraform plan says No changes, your infrastructure matches the configuration

What about the new policy flag?

Terraform 1.17 made Terraform Policy generally available, and terraform query -policies=DIR is supposed to evaluate the discovered resources against your policies before you import anything. I wrote a small policy that requires an env and an owner tag on every instance, downloaded the tfpolicy-plugin binary that Terraform wants on the PATH, and ran it:

Terminal: terraform query -policies fails with Failed to setup Terraform Policy connection, entitlement check failed, client did not supply entitlement information

The policy plugin checks an entitlement against an HCP Terraform or Terraform Enterprise organisation before it evaluates anything, and it refuses to start without one. With no terraform login and no cloud backend configured, it will not run locally. The plugin zip even ships a TermsOfEvaluation.txt. So the GA announcement is true, but “run policies on your laptop against a local state” is not what shipped, at least not in 1.17.0.

For a tagging check that does not need an organisation, the state is already JSON:

terraform show -json \
  | jq -r '.values.root_module.resources[]
           | select(.type=="aws_instance" and .values.tags.owner==null)
           | .address'

Terminal: the jq query lists aws_instance.forgotten, aws_instance.jump_host and aws_instance.test_box as instances with no owner tag

Three of the five instances have no owner. Now that they are in Terraform, adding the tag is a one-line change and a plan that shows exactly one update per instance.

What I would do on a real account

Run terraform query without -generate-config-out first and read the list. It is read only, it is fast, and it is the moment to notice resources you did not know existed. Then generate into a scratch directory with its own state, not your production workspace, until the plan shows zero changes. Expect to clean the generated file; the conflicts above are predictable and a short script handles them. Count the state entries against the number of real things before you apply, and keep one list block per set of resources so you never count eleven when you have eight.

The lab is throwaway: docker rm -f moto and delete the directory. Nothing in it needed credentials, which is the nice part about rehearsing this somewhere that cannot terminate anything.