Default value with object not working

Only one stickiness block can be passed in, I want it to be optional, and only the type is a required argument. How do I make the rest be optional?

main.tf:

module "ecs_alb_haproxy" {
  source = "../aws-alb"

  stickiness = {
    type = "lb_cookie"
  }
}

aws-alb/var.tf:

variable "stickiness" {
  description = "Should we use sticky sessions?"

  type = object({
    type            = string
    cookie_duration = number
  })

  default = {
    type            = "lb_cookie"
    cookie_duration = 86400
  }
}

aws-alb/main.tf:

resource "aws_lb_target_group" "target_group" {
  dynamic "stickiness" {
    for_each = var.stickiness
    content {
      type            = stickiness.value["type"]
      cookie_duration = stickiness.value["cookie_duration"]
    }
  }
}

error:

Error: Invalid value for module argument

  on ../modules/crossref-api/main.tf line 294, in module "ecs_alb_haproxy":
 294:   stickiness = {
 295:     type = "lb_cookie"
 296:   }

The given value is not suitable for child module variable "stickiness" defined
at ../modules/aws-alb/variables.tf:51,1-22: attribute "cookie_duration" is
required.

Hi @throwaway8787,

While the default value here means that assigning the variable is optional, individual object attributes are not optional. There currently is the Optional Object Type Attributes Experiment, but that doesn’t do quite what you are looking for, and it is likely to change before it’s final incarnation.

The usual way to pass in a value which you want to leave un-assigned is to use null, meaning the following would be valid

module "ecs_alb_haproxy" {
  source = "../aws-alb"

  stickiness = {
    type = "lb_cookie"
    cookie_duration = null
  }
}

If you want to ensure that there is always a default value for cookie_duration even if the given value is null, you would need to process that in a separate expression, usually assigned to a local value within the module.

1 Like