Dynamizing the code with variables and interpolation functions

When writing Terraform code, it is important to take into account from the beginning that the infrastructure that will host an application is very often the same for all stages, but only some information will vary from one stage to another, such as the name of the resources and the number of instances.

To give more flexibility to the code, we must use variables in the code with the following steps: 

  1. Declare the variables by adding the following sample code in the global Terraform code, or we can add it in another file (such as variables.tf) for better readability of the code:
variable "resource_group_name" {
description ="Name of the resource group"
}

variable "location" {
description ="Location of the resource"
default ="West Europe"
}

variable "application_name" {
description ="Name of the application"
}
  1. Instantiate their values in another file, .tfvars, named terraform.tfvars with the syntax, variable_name=value, like the following:
resource_group_name ="bookRg"
application_name ="book"
  1. Use these variables in code with var.<name of the variable>; for example, in the resource group Terraform code, we can write the following:
resource "azurerm_resource_group" "rg" {
name = var.resoure_group_name
location = var.location
tags {
environment = "Terraform Azure"
}
}

In addition, Terraform has a large list of built-in functions that can be used to manipulate data or variables. To learn more about these functions, consult the documentation here: https://www.terraform.io/docs/configuration/functions.html.

Of course, there are many other good practices, but these are to be applied from the first lines of code to make sure that your code is well maintained.

The complete final code of this sample is available here:  https://github.com/PacktPublishing/Learning_DevOps/tree/master/CHAP02/03-terraform_vars_interp.

We have written a Terraform script, with best practices, which allows us to create a simple cloud infrastructure in Azure that provides a network and a virtual machine. Let's now look at how to run Terraform with our code for provisioning this infrastructure.