terraformterraform-provider-awshcl

How to pass dynamic variable to import statement of Terraform


In the Terraform configuration script for dynamodb.tf, I am importing table resource to the Terraform state. The problem is for each environment the table resource that is being imported differs based on its environment value. For example in dev env, the table name is hello-dev-world, whereas in stage env the table name is hello-stage-world. Based on this I am using import statement as below:

 import {
  id = "hello-${lcl.env_stack}-world"
  to = aws_dynamodb_table.tf-hello-world
}

But the build fails with the below error for the variable used in id:

Error: Unsuitable value type
Unsuitable value: value must be known

However the build succeeds if I use hardcoded value in place of lcl.env_stack. Could you please let me know if there a way to pass in dynamic value in the id of import statement? If not possible is there another way to implement this scenario?


Solution

  • You need to be on terraform v1.6.0 or higher to be able to use a dynamic value for a terraform import block, but the value must be known at plan time (see here and here).

    Also, your interpolation uses ${lcl. env_stack} while it should be ${local.stack}.

    On a side note, oftentimes one can "convert" a value not known at plan time with one that is using some trickery (e.g. for GCP resources you might be able to construct the resource's self_link using only known values).