Pass list of objects (list of maps) variable to terraform via TF_VAR

Viewed 41

What is the correct way to pass a variable with type "list of objects" to terraform via an environment TF_VAR_ variable?

If I define the variable in the variables.tf or in .tfvars files as such

containers = [  
    {    
        "container_access_type": "private",
        "metadata": {},
        "name": "20220909-001"
    }
]
variable "containers" {
  description = "containers"
  default = [
    {
      "container_access_type": "private",
      "metadata": {},
      "name":"20220909-001"
    }
  ]

everything works and in the terraform console the variable is shown as

> var.containers
[
  {
    "container_access_type" = "private"
    "metadata" = {}
    "name" = "20220909-001"
  },
]

but if I declare the environment variable export TF_VAR_containers='[{"container_access_type":"private","metadata":{},"name":"20220912-001"},]' I get the error

The given value is not suitable for child module variable "containers" defined at terraform/modules/stco/storageContainer/variables.tf:1,1-22: list of object required.

and the variable is shown as

> var.containers
"[{\"container_access_type\":\"private\",\"metadata\":{},\"name\":\"20220912-001\"},]"

(the comma at the end makes no difference, I still get the error).

What is the proper way to pass such variable?

1 Answers

Thanks @jordanm, I needed to add the type of the variable:

variable "containers" {
  description = "containers"
  type = list(object({
    container_access_type = string,
    metadata = object({}),
    name = string
  }))
  default = [
    {
      "container_access_type": "private",
      "metadata": {},
      "name":"20220909-001"
    }
  ]
}

Related