slide

Terraform fot d floor()

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

What is it?

Function name: floor(float)

Returns: Rounds down to the closest integer, unless the float is already an integer value. Will attempt to perform implicit conversion of other data types to float prior to conversion.

Example:

variable "floor" {
  default = "3.14159"
}

# Returns 3
output "floor_output" {
  value = "${floor(var.floor)}"
}

Example file:

##############################################
# Function: floor
##############################################
##############################################
# Variables
##############################################
variable "floor" {
  default = true
}

##############################################
# Resources
##############################################

##############################################
# Outputs
##############################################
output "floor_output" {
  value = "${floor(var.floor)}"
}

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

terraform apply -var 'floor=5.9'
terraform apply -var 'floor=-5.9'
terraform apply -var 'floor=3.1'
terraform apply -var 'floor=-3.1'
terraform apply -var 'floor="-1"'
terraform apply -var 'floor="String"'
terraform apply

Why use it?

Floor is a fairly common mathematical device. If you are going to be manipulating float values and need an integer, floor might suit your needs.

Lessons Learned

I learned in the process that there is an implicit conversion of boolean true to float as 1 and false to float as 0. This conversion only happens when using a default value or passing the value in a tfvars file. True or false passed in the -var argument will be treated as a string without conversion. Strings will be converted to float if it’s a number, but not if it’s regular text. Negative numbers are rounded down away from 0, so -5.9 is rounded down to -6.

Coming up next is the flatten() function.