TheVillageIdiot
TheVillageIdiot

Reputation: 40527

terraform validation not short circuiting OR (||) condition

I have this variable declaration for azurerm_app_service:

variable "site_config_application_stack" {
  type = object({
    current_stack  = optional(string)
    dotnet_version = optional(string)
    node_version   = optional(string)
  })

  description = <<EOF
  var.site_config_application_stack = {
      current_stack = One of the following: dotnet, dotnetcore, node, python, php, and java.
      dotnet_version = One of the following: v2.0,v3.0,core3.1, v4.0, v5.0, and v6.0.
      node_version = One of the following: ~12, ~14, and ~16.
    }  
  EOF

  validation {
    condition     = var.site_config_application_stack.dotnet_version==null || contains(["v2.0", "v3.0", "core3.1", "v4.0", "v5.0", "v6.0"], var.site_config_application_stack.dotnet_version)
    error_message = "The dotnet_version should be one of the following: v2.0,v3.0,core3.1, v4.0, v5.0, and v6.0."
  }

   validation {
    condition     = var.site_config_application_stack.node_version==null || contains(["~12", "~14","~16"], var.site_config_application_stack.node_version)
    error_message = "The `node_version` should be one of the following: ~12, ~14, and ~16."
  }
 
  validation {
    condition     = var.site_config_application_stack.current_stack==null || contains(["dotnet", "dotnetcore", "node", "python", "php", "java"], var.site_config_application_stack.current_stack)
    error_message = "The `current_stack` should be one of the following: dotnet, dotnetcore, node, python, php, and java."
  }
}

When I try to create resource with code:

module "example_app"{
    .....
    site_config_application_stack = {
        current_stack  = "dotnetcore"
        dotnet_version = "v6.0"
    }
    .....
}

It is giving me the following error:

Error: Invalid function argument
│
│   on ..\..\platform.terraform.modules\app_service\variables.tf line 108, in variable "site_config_application_stack":
│  108:     condition     = var.site_config_application_stack.node_version==null || contains(["~12", "~14","~16"], var.site_config_application_stack.node_version)
│     ├────────────────
│     │ var.site_config_application_stack.node_version is null
│
│ Invalid value for "value" parameter: argument must not be null.

Should not var.site_config_application_stack.node_version==null satisfy the check?

Currently I've removed the validation, but would love to have a workaround!

Upvotes: 1

Views: 793

Answers (1)

Marcin
Marcin

Reputation: 238957

It fails, because you can't use null value in contains. You have to use try:

    condition     = var.site_config_application_stack.node_version==null || try(contains(["~12", "~14","~16"], var.site_config_application_stack.node_version), true)

Upvotes: 1

Related Questions