slide

Terraform fot d min()

Ned Bellavance
2 min read

Cover

This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the min() function. The example file is on GitHub here.

What is it?

Function name: min(float1, float2, float3,…)

Returns: Takes a list of numeric values and returns the lowest value of the set.

Example:

# Returns 0
output "min_output" {
  value = "${min("0","2","3.14159")}"
}

Example file:

##############################################
# Function: min
##############################################
##############################################
# Variables
##############################################
variable "min1" {
  default = false
}

variable "min2" {
  default = false
}
variable "min3" {
  default = false
}
variable "min4" {
  default = false
}
##############################################
# Resources
##############################################

##############################################
# Outputs
##############################################
output "min_output" {
  value = "${min(var.min1,var.min2,var.min3,var.min4)}"
}

Run the following from the min folder to get example output for a number of different cases:

#Regular values
terraform apply -var 'min1=5.9' -var 'min2=4.9' -var 'min3=6.9' -var 'min4=5.4'

#Negative values
terraform apply -var 'min1=-5.9' -var 'min2=5.9' -var 'min3=3.9' -var 'min4=-3.9'

#Same values
terraform apply -var 'min1=5.9' -var 'min2=5.9' -var 'min3=5.9' -var 'min4=5.9'

#Longer decimal point max out at 15
terraform apply -var 'min1=5.1123456789123456' -var 'min2=5.1123456789123455' -var 'min3=5.1123456789123454' -var 'min4=5.1123456789123453'

#Ints
terraform apply -var 'min1=5' -var 'min2=6' -var 'min3=7' -var 'min4=8'

Why use it?

I guess you’ve got a bunch of floats and need to know which one is the smallest. Really this is just a pass through of a basic function in the Go Math package. I’ve never had to use it, but that doesn’t mean others won’t. The functionality is a little weird to me, as I’ll explain in a moment.

Lessons Learned

There wasn’t much to get excited about here. I tried using some really long floats and it appears that the float type is a double, meaning it can go up to about 16 decimal places of precision. That should be more than enough for anything you are doing in Terraform. The thing I don’t like about the function is that it won’t take numbers in a list. You have to submit individual float values. You could use the sort function on a list and take the first or last element, but that is for lexographical sorting, not for numerical sorting. I’m guessing the two are a bit different. I’ll test that out when I get to sort.

Coming up next is the md5() function.