No dependencies in state after importing resources

How do I import a resource while also including dependencies? If I specify an attribute from another resource, and then import it by id, there is no dependency that shows up in state.

My use case is migrating an existing set of infrastructure to TF management. I did this by:

  1. Create a blank environment that is managed by TF
  2. Create each piece from the prod env in the blank one using HCL
  3. Verify that the resource layout / attributes of the two environments are identical
  4. Back up the copy-cat tfstate, start with no state and import each resource from prod.

This worked great, except that when I diff the copy-cat state and the new state that is created after I imported everything, the new state is missing all the "dependencies": [] blocks.

I verified that this is an issue by running terraform destroy -target [critical piece] against both states. The original copy cat state shows that I would be destroying pretty much all of the infrastructure, whereas the new imported state shows that I would only be destroying the piece specified.

Is there a way to import resources while intuiting its dependencies, the same way as it would be if it were simply created?

Hi @isaiahtaylor,

Unfortunately as you’ve seen terraform import can’t “see” dependencies because it is, aside from an initial simple safety-check, a state-only operation that doesn’t require a complete configuration.

Terraform typically re-analyzes the dependencies for each new operation, so this should only be a problem if you terraform import and then immediately terraform destroy, before Terraform has had an opportunity to incorporate the dependencies from configuration into the state.

Running at least one terraform apply that includes changes that cause a new state snapshot should cause Terraform to build that new snapshot from what it learned in configuration, thus filling in those missing dependencies.

1 Like

Thank you @apparentlymart! That is very helpful and answers my question. I will test it out soon.