hashicorp / hcl

HCL is the HashiCorp configuration language.
Mozilla Public License 2.0
5.27k stars 590 forks source link

cmd/hcldec: evaluating variables #499

Open caruccio opened 2 years ago

caruccio commented 2 years ago

I'd like to validate variable blocks in order to require all variables to have a description field. I'is part of the validation stage for my CI pipeline.

This is the input I'm going to receive from my user:

# uservars.tf
variable "one" {
  description = "One variable"
  type        = string
}

variable "two" {
  description = "Another variable"
  type        = number
  default     = 2
}

And this is the spec I've got so far.

# variables.hcldec
block_map {
    block_type = "variable"
    labels = ["name"]

    object {
        attr "description" {
            type     = string
            required = true
        }
        attr "type" {
            type     = any
            required = true
        }
        attr "default" {
            type     = any
            required = false
        }
    }
}

However type=any inside a block_map is not allowed, which produces the error below:

$ hcldec -s variables.hcldec uservars.tf
Error: Invalid block_map spec

  on vars.hcldec line 1, in block_map:
   1: block_map {

A block_map spec may not contain attributes with type 'any'.

Any tips?

PS:

Changing variables to use the now deprecated quoted type constraints (type = "string" and type = "number") does works as expected, but since this syntax is deprecated we are not allowed to use it anymore.

$ hcldec -s variables.hcldec uservars.tf
{"one":{"description":"One variable","type":"string"},"two":{"default":"2","description":"Abother variable","type":"number"}}
kmoe commented 2 years ago

Thanks for the well-written issue. The block_map spec type is not going to work, for the reason given in the error message: including dynamic (any) types inside a map type definition will lead to inconsistent map element types when the map is fully evaluated.

I think the right type for representing this structure may be hcldec.BlockObjectSpec, which is not currently available in cmd/hcldec. I'm not familiar enough with these packages to say that this will work for sure.