Manage multiple workspaces from a single configuration file in terraform

618 Views Asked by At

I want to create two different workspaces on Terraform Cloud: One for DEV environment, the other for PROD environment.

I am trying to create them hust using a single configuration file. The infrastructure will be the same just in two different Azure subscriptions with different credentials.

Here the code I am trying:

terraform {
  required_version = ">= 1.1.0"
  
  required_providers {
    #https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.40.0"
    }
  }
  
  cloud {
    organization = "mycompany"
    
    workspaces {
      tags = ["dev", "prod"]
    }
  }
}

I am watching the documentantion. It seems like inside the cloud -> workspace command I just can use either name or tags attributes. It is required I have at least one of them in my configuration.

Now in my Terraform Cloud account, I have two workspaces: 1 with the tag prod and one with the tag dev.

I set the envinroment variable:

$Env:TF_WORKSPACE="mycompany-infrastructure-dev"

And I try to initialize Terraform Cloud:

terraform init

But I get this error:

Error: Invalid workspace selection Terraform failed to find workspace "mycompany-infrastructure-dev" with the tags specified in your configuration: │ [dev, prod]

How can I create one configuration that I can use with different environment/workspaces?

Thank you

2

There are 2 best solutions below

0
On

First, I ran the similar code as yours in my environment and received an error shown below: It prompted me to use terraform login to generate a token for accessing the organization on Terraform Cloud.

The login was successful, and the browser generated an API token.

enter image description here

Token received and entered.

Logged into Terraform cloud as shown:

enter image description here

In Terraform Cloud -> Organizations, I created a new organization:

enter image description here

Script for creating different workspaces from a single configuration file:

cloud {
    organization = "mycompanyone"
    
    workspaces {
      tags = ["dev", "prod"]
      }
      }

Taken your script and made a few changes as seen below:

enter image description here

Terraform will prompt for basic concerns while initializing, as shown here.

enter image description here

Now run terraform init or terraform init -upgrade.

terraform initialized successfully:

enter image description here

0
On

The reason you have this issue is that to match a workspace that workspace must have ALL the tags you specify.

So instead of having dev and prod tags have tags that uniquely describe the workspace. E.g. my-company, infrastructure. Then make sure that you create two workspaces with different names that both have those tags. Then you can target that workspace with the TF_WORKSPACE environment variable.