Use Terraform for deploying resources in multiple environment

Jaseetha Satkurunathan
2 min readOct 27, 2023

--

In my previous post azure resource deployment, I laid the groundwork by hardcoding values into our main.tf file. This approach was designed for clarity, focusing on grasping the Terraform workflow. However, in practical scenarios, we often need to deploy to multiple environments, such as development, staging, and production. This article delves into how we can adapt and replicate our setup for these diverse environments, taking us from tutorial to real-world applicability.

In this article, we explore how to use the variable.tf file paired with terraform.tfvars for multiple environment.

Introducing variable.tf ,dev.tfvars prod.tfvarsfiles where variable.tf acts as a declaration hub, defining variables with names, types, and optional default values. This centralizes variable management. Meanwhile, .tfvars assigns values to these variables, allowing for easy, environment-specific variable configuration. This separation streamlines the handling of variables across various environments by employing multiple .tfvars files.

Below is the piece of code from my previous post Create Azure Resources using terraform main.tf for creating resource group .

resource "azurerm_resource_group" "demo_rg" {
name = "RG_RnD_Demo_Terraform"
location = "West Europe"
}

Required steps

  1. Variables Defined: We create a variable.tf file, where we declare essential variables like "name" and "location."
  2. Customization by Environment: To cater to distinct environments (e.g., development and production), we craft separate .tfvars files like dev.tfvars and prod.tfvars. These files are the keys to tailoring configurations based on each environment's unique requirements.
  3. Update Main Configuration: In our main.tf file, we make a crucial modification. Instead of hardcoding values, we now utilize the variables declared in variable.tf. This approach promotes reusability and makes the configuration more adaptable.

Here’s a snippet of what our updated configuration files look like, specifically tailored for creating an Azure resource group.

4. After validate Create plan for development and production environment as below

terraform plan -out dev.tfplan -var-file='dev.tfvars'
output for terraform plan for developement environment
terraform plan -out dev.tfplan -var-file='prod.tfvars'
output for terraform plan for production environment

5. Deploy resources in Azure

terraform apply -var-file='dev.tfvars'
terraform apply -var-file='prod.tfvars'

--

--

Jaseetha Satkurunathan

DevOps Engineer | DevAIOps Enthusiast | Multi-cloud Architect