How to avoid code duplication for input variable declaration/instantiation in Terraform?

Viewed 23

I want to create a variable 'blueprint' and instantiate it several times. How do I achieve this?

Example :

my_project
|--main.tf
|--variables.tf
|--variables.tfvars
  • In the main.tf I declare resources that use variables,
  • In variables.tf module I want this sample variable
variable "project_info" {
  type = object({
    name = string
    id   = string
  })
}
  • In variables.tfvars I want this (Kind of)
project_1_info = {
  name = "prj-1"
  id   = "prj-1-192388"
}

project_2_info = {
  name = "prj-2"
  id   = "prj-2-120917"
}

At the moment, what I declare in the variables.tf module is the following :

variable "project_1_info" {
  type = object({
    name = string
    id   = string
  })
}

variable "project_2_info" {
  type = object({
    name = string
    id   = string
  })
}

Which I find quite repetitive by duplicating declarations, makes maintenance and readability worse.

Any suggestions? Can this even be achieved with HCL?

1 Answers

Usually you would use map for that:

variable "project" {
  type = map(object({
    name = string
    id   = string
  }))
}

with a value:

project = {
  project1name = {
      name = "prj-1"
      id   = "prj-1-192388"
  },
  project2name = {
      name = "prj-2"
      id   = "prj-2-192388"
  },
  project3name = {
      name = "prj-3"
      id   = "prj-3-192388"
  }
}
Related