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 (HCL2) 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>
This name should be entirely in uppercase.
The source code for this recipe is available at https://github.com/PacktPublishing/Terraform-Cookbook/tree/master/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:
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 (see the left menu).