Terraform Math fundamentals

Terraform, an infrastructure-as-code tool, provides several built-in functions for performing various mathematical operations. These functions are handy for manipulating numerical values within your Terraform code. Here are some of the common math functions available in Terraform.

  1. max : returns the maximum value among the given set of numbers, refer ... to expand the collection to individual argument.

     variable "list_of_numbers" {
         type = list(number)
         default = [90, 20, 30, 40, 50]
    
     }
     # below output is working
     output "max_number" {
         value = max(var.list_of_numbers ...)
    
    1. ceil: returns next integer value to the given number.

       variable "number" {
           type = number
           default = 1.2   # returns 2
       }
       output "ceil_value" {
           value = "Given value is ${var.number} 
               and ceil value is ${ceil(1.5)}"
      
      1. floor: The floor function returns integer value less than or equal to a given number.

         variable "fnumber" {
           type    = number
           default = 5.89  # returns 5
         }
        
         output "floor_number" {
           value = "Given value is ${var.fnumber} and floor value is ${floor(var.fnumber)}"
         }
        
        1. signum(): Returns -1, 0, or 1 depending on the sign of the given number (-1 for negative, 0 for zero, and 1 for positive).

           signum(-5)  # Returns -1
          

5. date time function - though not a math function, thought of adding here for reference.

            print date and time
            output "date_and_time" {
                value = formatdate("EEE, DD-MM-YYYY hh:mm:ss", timeadd(timestamp(), "5.30h"))
            }
            # returns Wed, 21-02-2024 20:46:35