Conditional Terraform Import Blocks

I’m attempting to use the new ‘import’ block to import a manually created Route53 zone in AWS into my Terraform state.

I have a number of environments in which I’m running my TF deploy and this import block is only relevant for the ‘production’ environment. I therefore need to make this import block conditional.

I’ve attempted to do so using the ‘count’ and a local var to read my ‘environment’ variable:

locals {
  prod-env    = var.environment == "prod"
}

import {
  count       = local.prod-env ? 1 : 0
  to = aws_route53_zone.example
  id = "myhostedzoneid"
}

resource "aws_route_53_zone" "example" {
  count       = local.prod-env ? 1 : 0
  name = "example.com"
}

However, when I run a plan using this configuration I get the following error:

╷
│ Error: Unsupported argument
│ 
│   on hosted_zone.tf line 6, in import:
│    6:   count       = local.prod-env ? 1 : 0
│ 
│ An argument named "count" is not expected here.

Any better way to do this?

3 Likes

It’s not possible to make import blocks conditional - that means that if you’re accustomed to using the same code in multiple environments, differentiating only with variables and backend config, import blocks aren’t compatible with this workflow.

The only solution is to find a way external to Terraform, to only include the relevant .tf files when processing certain environments.

That’s a shame - I may raise an issue in the terraform repo to see if support could be added for that.

2 Likes

I’m 100% agree with the author of this thread. It is not even possible to pass variables, TF throws the following error:

│ Error: Variables not allowed

Sounds that this should be improved ASAP.

Thanks, best regards

2 Likes

I didn’t see an issue for count but here’s one for for_each: Plannable Import: Support for_each · Issue #33624 · hashicorp/terraform · GitHub

1 Like

Created for count, please support Plannable Import: Support count · Issue #34227 · hashicorp/terraform · GitHub by thumbs up.

Strange that this is not implemented initially.