Skip to content

variable validation fails on optional variables #30403

@philip-harvey

Description

@philip-harvey

When trying to perform variable validation on a variable with optional values Terraform returns an error, "This object does not have an attribute named XXXX" if any of the elements in the map are not set (set to null by being optional).
Tested with Terraform 1.1.2 and 1.1.4

Code to reproduce the issue:
main.tf:

terraform {
  experiments = [module_variable_optional_attrs]
}

variable "var1" {
  type = map(object({
    config_str = optional(string)
  }))
  validation {
    condition     = alltrue([for k in var.var1 : (k.config_str != "bad-config")])
    error_message = "Config_str must not be set to 'bad-config'."
  }
}

terraform.tfvars:

var1 = {
  config1 = {}
  config2 = {config_str = "good-config"}
}

Expected Behavior

Validation should pass or fail depending on the validation rule.

Actual Behavior

Terraform returns an error. e.g.

Error: Unsupported attribute
   on main.tf line 10, in variable "var1":
   10:     condition     = (var.var1.config_str != "bad-config")
     var.var1 is object with 1 attribute "config1"
 This object does not have an attribute named "config_str".

Steps to Reproduce

  1. terraform init
  2. terraform plan

Additional Context

As a work around it is possible to use try or lookup, but it gets a little ugly. e.g:

variable "var1" {
  type = map(object({
    config_str = optional(string)
  }))
  validation {
    condition     = alltrue([for k in var.var1 : (lookup(k,"config_str",null) != "bad-config")])
    error_message = "Config_str must not be set to 'bad-config'."
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugnewnew issue not yet triaged

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions