Terraform – FotD – max()

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 max() function. The example file is on GitHub here.

What is it?

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

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

Example:

# Returns 3.14159
output "max_output" {
  value = "${max("0","2","3.14159")}"
}

Example file:

##############################################
# Function: max
##############################################
##############################################
# Variables
##############################################
variable "max1" {
  default = false
}

variable "max2" {
  default = false
}
variable "max3" {
  default = false
}
variable "max4" {
  default = false
}
##############################################
# Resources
##############################################

##############################################
# Outputs
##############################################
output "max_output" {
  value = "${max(var.max1,var.max2,var.max3,var.max4)}"
}

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

#Regular values
terraform apply -var 'max1=5.9' -var 'max2=4.9' -var 'max3=6.9' -var 'max4=5.4'

#Negative values
terraform apply -var 'max1=-5.9' -var 'max2=5.9' -var 'max3=3.9' -var 'max4=-3.9'

#Same values
terraform apply -var 'max1=5.9' -var 'max2=5.9' -var 'max3=5.9' -var 'max4=5.9'

#Longer decimal point max out at 15
terraform apply -var 'max1=5.12345678912345' -var 'max2=5.123456789123456' -var 'max3=5.1234567891234567' -var 'max4=5.12345678912345678'

#Ints
terraform apply -var 'max1=5' -var 'max2=6' -var 'max3=7' -var 'max4=8'

Why use it?

I guess you’ve got a bunch of floats and need to know which one is the biggest. 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 merge() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.