Calling Terraform’s built-in functions
When provisioning infrastructure or handling resources with Terraform, it is sometimes necessary to use transformations or combinations of elements provided in the Terraform configuration.
For this purpose, the language supplied with Terraform includes functions that are built in and can be used in any Terraform configuration.
In this recipe, we will discuss how to use built-in functions to apply transformations to code.
Getting ready
To complete this recipe, we will start from scratch regarding the Terraform configuration, which will be used to provision a resource group in Azure. This resource group will be named according to the following naming convention:
RG-<APP NAME>-<ENVIRONMENT>
The result of this transformation will return a name that should be entirely in uppercase.
The source code for this recipe is available at https://github.com/PacktPublishing/Terraform-Cookbook-Second-Edition/tree/main/CHAP02/fct.
How to do it…
Perform the following steps:
- In a new local folder, create a file called
main.tf
. - In this
main.tf
file, write the following code:variable "app_name" { description = "Name of application" } variable "environement" { description = "Environement Name" }
- Finally, in this
main.tf
file, write the following Terraform configuration:resource "azurerm_resource_group" "rg-app" { name = upper(format("RG-%s-%s",var.app-name,var.environement)) location = "westeurope" }
How it works…
In Step 3, we defined the property name of the resource with a Terraform format
function, which allows us to format text. In this function, we used the %s
verb to indicate that it is a character string that will be replaced, in order, by the name of the application and the name of the environment.
Furthermore, to capitalize everything inside, we encapsulate the format
function in the upper
function, which capitalizes all its contents.
The result of executing these Terraform commands on this code can be seen in the following screenshot:
Figure 2.12: Terraform built-in function to capitalize text
Thus, thanks to these functions, it is possible to control the properties that will be used in the Terraform configuration. This also allows us to apply transformations automatically, without having to impose constraints on the user using the Terraform configuration.
See also
There are a multitude of predefined functions in Terraform. The full list can be found at https://www.terraform.io/docs/configuration/functions.html (navigate with the left menu to see all built-in functions):
- To read more details about the
format
function, refer to the documentation at https://www.terraform.io/language/functions/format. - To read more details about the
upper
function, refer to the documentation at https://www.terraform.io/language/functions/upper.