Home > other >  Getting minimum value by output block
Getting minimum value by output block

Time:08-31

I need to get minimum value in output block using variable type number with list

Terraform:

variable "ports" {
   type = list(number)
   default = [12,16,23]
}

output "ports_count" {
  value = length(var.ports)
}

output "ports_min" {
  value = min(var.ports)
}

Output

│ Error: Invalid function argument
│ 
│   on main.tf line 11, in output "ports_min":
│   11:   value = min(var.ports)
│     ├────────────────
│     │ var.ports is a list of number, known only after apply
│ 
│ Invalid value for "numbers" parameter: number required.

CodePudding user response:

Since output will require the value to be known, I suggest using local variables:

locals {
  ports = [12,16,23]
}

Then in the outputs, you would do the following:

output "ports_min" {
  value = min(local.ports...)
}

This will output 12. The ... is function expansion operator [1].


[1] https://www.terraform.io/language/expressions/function-calls#expanding-function-arguments

  • Related