mayank arora
mayank arora

Reputation: 117

terraform count index and length

Trying to create multiple private DNS zone

  1. non prod --> Dev,QA,UAT.
  2. prod --> Prd,DR

Resource should be created only if is_nonprod is set to 1. emphasized text(boolean value). Idea is to use count twice in resource block : once for boolean and once for length function.

resource "azurerm_private_dns_zone" "example" {
      
      count                  = var.is_nonprod ? 1 : 0 && length(var.env)
      name                   = var.env[count.index].npr
      resource_group_name    = "examplerg"
    }

variable file:

variable "env" {
  description = "List of routes to be added to the route table"
  default     = []
  type        = list(map(any))
}

variable "is_nonprod " {
    default = true
}

tfvars

env = [
  { npr = "qa" },
  { npr = "uat" },
  { npr = "dev" }
]

Error : The true and false result expressions must have consistent types. The given expressions are number and bool, respectively.

workaround :

resource "azurerm_private_dns_zone" "example" {
      
      count                  = var.is_nonprod ? 1 : 0 
      count                  = length(var.env)
      name                   = var.env[count.index].npr
      resource_group_name    = "examplerg"
    }

Error : The argument "count" was already set at main.tf:96,3-8. Each argument may be set only once.

Upvotes: 0

Views: 3765

Answers (2)

Sandeep
Sandeep

Reputation: 1

Seems like datatype conflicts. You can directly use count = var.is_nonprod ? length(var.env) : 0 and it should give you expected results.

Upvotes: 0

Matthew Schuchard
Matthew Schuchard

Reputation: 28854

var.is_nonprod ? 1 : 0 && length(var.env) does not look like the logic you want here based on what you described in the question. It seems like you really want var.is_nonprod ? length(var.env) : 0, which is also syntactically valid. The && operator inputs and returns booleans, which are not valid as an input type to the count metaparameter. count takes a number as input (typically the number of resources you want to manage), and not true or false.

Upvotes: 4

Related Questions