Home > Software engineering >  is there a way to concatenate multiple list variables in terraform locals
is there a way to concatenate multiple list variables in terraform locals

Time:01-19

i have 2 string list variables.

  • ["domain1", "domain2"]

  • ["log1", "log2", "log3"]

I need to concatenate these list like this:

  • "log-name/domain1/log1"
  • "log-name/domain1/log2"
  • "log-name/domain1/log3"
  • "log-name/domain2/log1"
  • "log-name/domain2/log2"
  • "log-name/domain2/log3"
variable domain_names {
    type=list(object({
        domain_name           = string
        elasticsearch_version = number
    }))
}
variable log_names {
  type = list(string) 
  default = [ "log1", "log2", "log3" ]
}
locals {
  log_template = [
    for d in var.domain_names : [
      for l in var.log_names : {
        log = "log-name/${var.domain_names[d].domain_name}/${var.log_names[l]}"
      }
    ]
  ]
}

and my terraform.tfvars:

domain_names = [ 
  { 
    domain_name = "domain1" 
    elasticsearch_version = "6.8" 
  }, 
  { 
     domain_name = "domain2" 
     elasticsearch_version = "6.8" 
  }, ]

when i apply this terraform code, i am getting this error:

Error: Invalid index
│ 
│   on elasticsearch_domain.tf line 99, in locals:
│   99:         log = "log-name/${var.domain_names[d].domain_name}/${var.log_names[l]}"
│     ├────────────────
│     │ var.domain_names is list of object with 1 element
│ 
│ The given key does not identify an element in this collection value: number required.
╵
╷
│ Error: Invalid index
│ 
│   on elasticsearch_domain.tf line 99, in locals:
│   99:         log = "log-name/${var.domain_names[d].domain_name}/${var.log_names[l]}"
│     ├────────────────
│     │ var.log_names is list of string with 4 elements
│ 
│ The given key does not identify an element in this collection value: a number is required.

what are the best practices for it? how can i concat these and use them in one resource like this:

resource "aws_cloudwatch_log_group" "log-groups" {

  name = ...
}

CodePudding user response:

You can use flatten and the following new version of your for loop to get your desired list:

locals {
  log_template = flatten([
    for d in var.domain_names : [
      for l in var.log_names : [
       "log-name/${d.domain_name}/${l}"
      ]
    ]
  ])
}
  • Related