Problem
After you successfully import a resource using the terraform import command, the resource does not appear when you run terraform state list. This issue often occurs when the resource configuration uses a for_each argument and you are importing a specific instance from that loop.
Cause
This behavior is due to how shells and the HashiCorp Configuration Language (HCL) parse strings. When you provide the resource address to the terraform import command, special characters such as double quotes (") in the address must be properly escaped to be interpreted correctly.
Solution
To ensure Terraform correctly parses the resource address and adds the imported resource to the state, you must escape the double quotes within the resource's key-value index address.
Consider the following resource configuration that uses for_each.
variable "instances" {
type = set(string)
default = ["instance1", "instance2", "instance3"]
}
resource "example_resource" "example" {
for_each = var.instances
name = each.key
}To import one of these resources, you must wrap the resource address in single quotes (') for the shell and use escaped double quotes (\") for the instance key.
$ terraform import 'example_resource.example["instance1"]' <resource-id-instance1>
Alternatively, you can escape the quotes for a shell that expects double quotes.
$ terraform import "example_resource.example[\"instance1\"]" <resource-id-instance1>
Outcome
After using the correctly escaped import command, the resource will be successfully added to the Terraform state. You can verify this by listing the resources in the state.
$ terraform state list
The output should now include the imported resource.
example_resource.example["instance1"]
Additional Information
For more details on string literals and escape sequences in HCL, refer to the official documentation on Expressions: Strings.