This post references Terraform version 0.11 and older. Check out the official docs for 0.12 and newer here
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 abs() function. The example file is on GitHub here.
Function name: abs(float) Returns: The absolute value of the float value passed to the function. Will attempt to perform implicit conversion of other data types to float prior to conversion. Example:
variable "negative_float" {
default = -3.14159
}
# Returns 3.14159
output "plus_float" {
value = "${abs(var.plus_float)}"
}
Here’s a generalized example:
##############################################
# Function: abs
##############################################
##############################################
# Variables
##############################################
variable "abs" {
default = false
}
##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "abs_output" {
value = "${abs(var.abs)}"
}
Run the following from the abs folder to get example output for a number of different cases:
terraform apply -var 'abs=5'
terraform apply -var 'abs=-5'
terraform apply -var 'abs=3.14159'
terraform apply -var 'abs=3.14149'
terraform apply -var 'abs="-1"'
terraform apply -var 'abs="String"'
terraform apply
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 agrument 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. Fun stuff!
Coming up next is basename().
What's New in the AzureRM Provider Version 4?
August 27, 2024
Debugging the AzureRM Provider with VSCode
August 20, 2024
State Encryption with OpenTofu
August 1, 2024
July 24, 2024