Skip to content

Implement Variables

Now that you have a basic Terraform running, you'll variablize your inputs to our Terraform code to make it more modular and reusable. Variables can be defined in many ways within Terraform, including a variables file, environment variables, and flags.

Refactor to consume variables

Refactor main.tf to utilize variables. Here is an example of how main.tf calls a variable.

resource "azurerm_app_service_plan" "dojo_app_service_plan" {
  name                = var.app_service_plan_name
  ...
}

Make sure that important hard-coded values have been replaced with var.variable-name throughout the Terraform code.

Create the variables file

After you have variablized your inputs to your azure app service and azure app service plan, you'll need to define your variables. Update the file called variables.tf which is where you'll define your variables as well as the types of input they'll accept.

Below is an example of a variable definition.

variable "resource_group_name" {
  description = "The resource group name used for all resources"
  type        = string
}

Make sure that you have defined all variables that you are using in main.tf in your variables.tf file.

Create the variable definition file

Now that you have updated your variables.tf for the variable definitions, you'll also need a file that has the input values for those variables. Update the additional file called workshop.auto.tfvars which is where you'll create a sample input file to pass to our terraform.

Below is an example of how to fill in workshop.auto.tfvars with values for your variables.

resource_group_name   = "RG-Dojo-Sandbox"

Although this file is good for one environment configuration, sometimes you'll need multiple configurations for multiple environments like dev, model, prod, etc, which is what we will cover in the next lab.

Defining variables in Terraform. A variables.tf file is used to define the variables type and optionally set a default value, whereas a .tfvars file is used to set the actual values of the variables. (docs)

Execute Terraform

Run this Terraform lifecycle and check between each part the output.

terraform fmt
terraform init
terraform plan
terraform apply
terraform destroy