Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a default field for type = map(object()) in variavles.tf

Tags:

terraform

I have the following variable in my variables.tf file:

variable "accounts" {
   type = map(object({
       field1       = string,
       field2       = list(string),
       field3       = list(string),
       field4       = list(string),
       field5       = string
  }))
 }

I need to add a default field so that my users don't have to specify every field. For example, if field2 is an empty list, I don't want the user to have to define field2 =[]

I've tried some variations of the following but nothing seems to work.

default = {
  default = {
    "field1"   = "",
    "field2"   = [],
    "field3"   = [],
    "field4"   = [],
    "field5"   = ""
  }
}

Anyone have any idea of how to do it or know if it's even possible?

like image 791
Gabrielbu Avatar asked Jul 13 '26 03:07

Gabrielbu


1 Answers

It is now possible to specify a default value for Terraform's optional(...) type constraint (as of Terraform 1.3). To solve the problem in the question posed:

variable "accounts" {
   type = map(object({
       field1       = string
       field2       = optional(list(string), [])
       field3       = list(string)
       field4       = list(string)
       field5       = optional(string, "")
  }))
 }

Reference documentation: https://developer.hashicorp.com/terraform/language/expressions/type-constraints#optional-object-type-attributes

like image 160
Supremacy Avatar answered Jul 16 '26 08:07

Supremacy