Terraform import fails even though the resources being imported does not depend on the error that is thrown

Hi,

I am importing a resource in my state file using this command:

tf import "module.opensearch.module.ecr[0].aws_ecr_repository_policy.policy[0]" "logstash-policy"

But, I am getting this error:

╷
│ Error: Invalid for_each argument
│ 
│   on .terraform/modules/opensearch.certificate/acm_certificate/main.tf line 14, in resource "aws_route53_record" "cert_validity":
│   14:   for_each = {
│   15:     for domain_validation_option in aws_acm_certificate.cert.domain_validation_options : dvo.domain_name => {
│   16:       name   = domain_validation_option.resource_record_name
│   17:       record = domain_validation_option.resource_record_value
│   18:       type   = domain_validation_option.resource_record_type
│   19:     }
│   20:   }
│     ├────────────────
│     │ aws_acm_certificate.cert.domain_validation_options is a set of object, known only after apply
│ 
│ The "for_each" map includes keys derived from resource attributes that cannot be determined until apply, and so Terraform cannot determine the full set of keys that will identify the instances of this resource.
│ 
│ When working with unknown values in for_each, it's better to define the map keys statically in your configuration and place apply-time results only in the map values.
│ 
│ Alternatively, you could use the -target planning option to first apply only the resources that the for_each value depends on, and then apply a second time to fully converge.

When I run terraform plan, it runs successfully. Also, these two resources are not even related to each other. How is the import failing here?

Terraform version: 1.7.2

The legacy import command can’t take into account other parts of the configuration which may not yet be known, especially if you are trying to import into a resource with multiple instances.

The only way to plan new actions in conjunction with importing resources is to also plan the import using an import block.

1 Like