Pass/Override Terraform object variable via command line

Viewed 390

I have a Terraform configuration (v0.14, AWS provider 3.32.0) in which I have defined the parameters for certain resource types as objects (input variables). Here is an (simplified) example:

variable "docker_config" {
  type = object({
    internal = number
    external = number
    protocol = string
  })
  default =
    {
      internal = 8300
      external = 8300
      protocol = "tcp"
    }
}

However, I would like to be able to override individual values via command line or environment variable. Can I overwrite individual values of the object without having to pass the whole object? So, use default values and override them as needed:

e. g. TF_VAR_docker_config.internal = 1234

or TF_VAR_docker_config = "{internal = 1234}"

And this would result in:

    {
      internal = 1234
      external = 8300
      protocol = "tcp"
    }

My tests did not work. Is it possible? If yes, how?

1 Answers

Sadly, you can't do this directly. In near future optional should be added to object which will simplify this.

For now, a non-perfect workaround could be to use merge with regular map:

variable "docker_config_default" {
  type = object({
    internal = number
    external = number
    protocol = string
  })
  
  default = {
      internal = 8300
      external = 8300
      protocol = "tcp"
    }
}

variable "docker_config" {
  type = map
  
  validation {
    # condition is not perfect and suited only for one 
    # attribute overwrite
    condition     = (can(var.docker_config["internal"]) 
                    || can(var.docker_config["external"]) 
                    || can(var.docker_config["protocol"]))
    error_message = "Must have internal, external or protocol."
  } 
}

locals {
  docker_config = merge(var.docker_config_default, var.docker_config)
}

output "test" {
  value = local.docker_config
}

And you just use local.docker_config in your code.

Related