Introduction
After successfully importing a resource using Terraform's import command, users may encounter a situation where the imported resource is not visible in the state list, despite the successful import operation. This issue typically arises when the resource is imported using a key-value index address, within a for_each
loop in the resource configuration.
Cause
The reason for this discrepancy lies in the parsing behavior of HashiCorp Configuration Language (HCL), which Terraform uses for its configuration files.
When utilizing the for_each
loop in a resource configuration, the use of double quotation marks ("") within the resource address can cause the parsing errors.
Solution
To ensure the successful reflection of the imported resource in the Terraform state list, users need to properly escape the double quotation marks (" ") within the resource address by using a backslash ( \ ) before each double quotation mark.
Example: Consider a resource configuration where a for_each loop is used and the resource address which includes double quotation marks:
variable "instances" {
default = toset(["instance1","instance2","instance3"])
}
resource "example_resource" "example" {
for_each = var.instances
name = each.key
}
To import this resource successfully and ensure its visibility in the Terraform state file, the resource address should be escaped with backslashes:
terraform import "example_resource.example[\"instance1\"]" <resource-id-instance1>
By adding backslashes before each double quotation mark, Terraform correctly parses the resource address, enabling the imported resource, to be properly managed within the state
References
https://developer.hashicorp.com/terraform/language/expressions/strings#escape-sequences