Terraform workspaces – Infrastructure as Code (IaC) with Terraform-1

Software development requires multiple environments. You develop software within your workspace, deploy it into the development environment, unit test it, and then promote the tested code to a test environment. Your QA team will test the code extensively in the test environment, and once all test cases pass, you can promote your code to production.

That means you must maintain a similar infrastructure in all environments. With an IaC tool such as Terraform, infrastructure is represented as code, and we must manage our code to fit multiple environments. But Terraform isn’t just code; it also contains state files, and we must maintain state files for every environment.

Suppose you want to create three resource groups, terraform-exercise-dev, terraform-exercise-test, and terraform-exercise-prod. Each resource group will contain a similar set of infrastructure with similar properties. For example, each resource group includes an Ubuntu Virtual Machine (VM).

A simple method to approach the problem is by creating a structure like the following:
├── dev
├── backend.tf
├── main.tf
├── terraform.tfvars
└── vars.tf
├── prod
├── backend.tf
├── main.tf
├── terraform.tfvars
└── vars.tf
└── test
├── backend.tf
├── main.tf
├── terraform.tfvars
└── vars.tf

Can you see the duplication? The same files occur multiple times, all containing the same configuration.
The only thing that might change is the terraform.tfvars file for each environment.

So, this does not sound like a great way to approach this problem, and that’s why Terraform provides workspaces for it.

Terraform workspaces are nothing but independent state files. So, you have a single configuration and multiple state files for each environment. Sounds simple, right? Let’s have a look.

Another way to represent the same configuration by using Terraform workspaces is the following:

├── backend.tf
├── main.tf
├── terraform.tfvars
└── vars.tf

Now, this looks simple. It just contains a single set of files. Let’s have a look at each of them to understand them better.

To access the resources for this section, cd into the following:
$ cd ~/modern-devops/ch8/terraform-workspaces/

The main.tf file contains a resource_group resource with a name that includes an environment suffix, along with other resources that we need to create within the resource group, such as the VNet, subnet, and VM, something like the following:

resource “azurerm_resource_group” “main” {
name        = “${var.rg_prefix}-${terraform.workspace}”
location = var.rg_location
}
resource “azurerm_virtual_network” “main” {

}
resource “azurerm_subnet” “internal” {

}
resource “azurerm_network_interface” “main” {

}
resource “azurerm_virtual_machine” “main” {

}

Leave a Reply

Your email address will not be published. Required fields are marked *