Fuczak
Fuczak

Reputation: 350

Terraform cloud config dynamic workspace name

I'm building CI/CD pipeline using GitHub Actions and Terraform. I have a main.tf file like below, which I'm calling from GitHub action for multiple environments. I'm using https://github.com/hashicorp/setup-terraform to interact with Terraform in GitHub actions. I have MyService component and I'm deploying to DEV, UAT and PROD environments. I would like to reuse main.tf for all of the environments and dynamically set workspace name like so: MyService-DEV, MyService-UAT, MyService-PROD. Usage of variables is not allowed in the terraform/cloud block. I'm using HashiCorp cloud to store state.

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 2.0"
    }
  }

  cloud {
    organization = "tf-organization"
    workspaces {
      name = "MyService-${env.envname}" #<==not allowed to use variables
    }
  }
}

Update

I finally managed to get this up and running with helpful comments. Here are my findings:

Upvotes: 6

Views: 2728

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74299

It doesn't make sense to refer to terraform.workspace as part of the workspaces block inside a cloud block, because that block defines which remote workspaces Terraform will use and therefore dictates what final value terraform.workspace will have in the rest of your configuration.

To declare that your Terraform configuration belongs to more than one workspace in Terraform Cloud, you can assign each of those workspaces the tag "MyService" and then use the tags argument instead of the name argument:

  cloud {
    organization = "tf-organization"
    workspaces {
      tags = ["MyService"]
    }
  }

If you assign that tag to hypothetical MyService-dev and MyService-prod workspaces in Terraform Cloud and then initialize with the configuration above, Terraform will present those two workspaces for selection using the terraform workspace commands when working in this directory.

terraform.workspace will then appear as either MyService-dev or MyService-prod, depending on which one you have selected.

Upvotes: 4

Related Questions