Home > Mobile >  Terraform conditional quantity with for_each
Terraform conditional quantity with for_each

Time:01-28

I need an if statement with for_each. If it is non-prod create resource in a single subnet, if production create resources in both subnets:

locals {
  zone_data = {
    a = {
      subnet_id = data.aws_cloudformation_export.subnet1.value
    }
    b = {
      subnet_id = data.aws_cloudformation_export.subnet2.value
    }
  }
}

module "batch_server" {
     for_each = var.env_name == "non-prod" ? local.zone_data.a : local.zone_data
...

I get an error:

|----------------
    | local.zone_data is object with 2 attributes
    | local.zone_data.a is object with 1 attribute "subnet_id"

The true and false result expressions must have consistent types.
The given expressions are object and object, respectively.

I tried this:

for_each = var.env_name == "non-prod" ? [local.zone_data.a] : [local.zone_data]

and am getting similar error:

|----------------
    | local.zone_data is object with 2 attributes
    | local.zone_data.a is object with 1 attribute "subnet_id"

The true and false result expressions must have consistent types.
The given expressions are tuple and tuple, respectively.

Tried changing types but nothing seems to work

CodePudding user response:

I would suggest reworking the local variables a bit so you can use them based on the environment, e.g.:

locals {
  non_prod = {
    a = {
      subnet_id = data.aws_cloudformation_export.subnet1.value
    }
  }
  prod = {
    a = {
      subnet_id = data.aws_cloudformation_export.subnet1.value
    }
    b = {
      subnet_id = data.aws_cloudformation_export.subnet2.value
    }
  }
}

Then, in the module call you would do the following:

module "batch_server" {
     for_each = var.env_name == "non-prod" ? local.non_prod : local.prod
...

Alternatively, you could still use the same local variables, but adjust it to something like:

module "batch_server" {
     for_each = var.env_name == "non-prod" ? { for k, v in local.zone_data: k => v if k == "a" } : local.zone_data
...

CodePudding user response:

How about a lookup with var.env_name as the key?

variable "env_name" {
  type = string
  default = "non_prod"
}

locals {
  zone_data = {
    prod = {
      a = {
        subnet_id = data.aws_cloudformation_export.subnet1.value
      }
      b = {
        subnet_id = data.aws_cloudformation_export.subnet2.value
      }
    },
    non_prod = {
      a = {
        subnet_id = data.aws_cloudformation_export.subnet1.value
      }
    }
  }
}

module "batch_server" {
     for_each = lookup(local.zone_data, var.env_name)
...
  • Related