10. Built-In Functions
While Terraform is not an imperitive programming language such as Python, there are a number of functions you can use to manipulate variable values. These can be called when assigning values in a resource or data source, or when create locals. There are many more than we will discuss in this course, but here are a few common examples.
Mathematical Functions
ceil- Rounds a decimal number up to the nearest whole number, e.g.ceil(4.1)returns5floor- Rounds a decimal number down to the nearest whole number, e.g.floor(4.1)returns4parseint- Converts a number represented as a string into a number, based on a given base, e.g.parseint("100", 10)returns 10, butparseint("100", 2)returns 4
String Functions
replace- Replace all instances of a given substring within a string, e.g.replace("prp_123456", "prp_", "")returns"123456"lower- Converts a given string to all lower case, e.g.lower("BaNANas")returns "bananas"trimspace- Remove any whitespace (space, tabs, newlines etc.) from the start and end of a string, e.g.trimspace(" Hello, there \n\n")returns "Hello, there"
Collection Functions
compact- Takes a list of strings and returns a new list with any null or empty string elements removed, e.g.compact(["a", "", "b", null, "c"])returns["a","b","c"]concat- Takes two or more lists and combines them into a single list, e.g.concat(["a", ""], ["b", "c"])returns["a","","b","c"]length- Determines the length of a given list, map, or string, e.g.length(["a", "b"])returns2
File Functions
file- Load the contents of a local file, e.g.filecontent = file("${path.module}/data.txt")templatefile- Load the contents of a file and replace variable values from a given set, e.g.filecontent = templatefile("${path.module}/data.txt", my_vars)
Encoding Functions
jsondecode- Convert a json string into a Terraform variable, e.g.data = jsondecode(local.file_content)base64decode- Convert base64-encoded data into a regular UTF-8 string, e.g.base64decode("SGVsbG8gV29ybGQ=")returns"Hello World"
Type-Conversion Functions
tostring- Convert a numberl, or boolean into a string, e.g.tostring(1)returns"1"andtostring(true)returns"true"tobool- Convert the strings "true" or "false" into actual boolean values, e.g.tobool("true")returnstrue
These are a very small subset of all the functions you can use in Terraform, and you can find the full list here (opens in a new tab)
Exercise
Configure
In your main.tf create 3 local variables.
Update
Use at least one built-in function on each variable to change its value.
Outputs
Create outputs for the values. Although not necessary, but for standardization remember to add your outputs to your outputs.tf file.
Plan/Apply
Run terraform plan to show the outputs in the terminal. You can also run terraform apply and that will save the outputs to the Terraform state file.