Extracting variables from workspace name in TFC

Hi,

I have a question regarding Terraform Cloud (TFC) and its variable capabilities. Is it possible to define variables in TFC that can automatically extract specific information from the workspace name? using split, join functions?

For instance, let’s say my workspace naming convention follows the pattern “EnvName-region-projectName”. I would like to know if there is a way to extract the environment name and region from the workspace name itself and assign them directly to variables within TFC.

Based on my understanding, it is not currently possible to directly pass variables in Terraform Cloud (TFC) variables or even in Terraform variables. Is this correct?

Thank you for your assistance.

No, you’ll have to explicitly define variables with whatever literal values you want, indepently from whatever name the workspace happens to have.

1 Like

You can do this in TF Cloud.

There is a list of variables which can be used in this way. See Terraform Cloud's Run Environment - Runs - Terraform Cloud | Terraform | HashiCorp Developer.

So for workspace name you would create a variable like:

# tflint-ignore: terraform_naming_convention
variable "TFC_WORKSPACE_NAME" {
  default     = ""
  description = "Terraform Cloud variable which is automatically filled in."
  type        = string
}

That variable could then be used in your regular TF code with whatever string manipulation you fancy.

I, personally, use it to tag all available resources and identify the workspace they come from:

provider "aws" {
  default_tags {
    tags = {
      tf-cloud-workspace = var.TFC_WORKSPACE_NAME
    }
  }
}
1 Like

After implementing the suggestion, it worked perfectly. I wasn’t aware of these variables that could be exposed in TFC.
Thanks appreciate it @stewart.campbell

Another solution I’d like to share is the use of ${terraform.workspace} within your code, allowing you to expose the workspace name from Terraform Cloud (TFC). This enables us to access and extract any necessary values associated with it.

locals {
  workspace_name = "${terraform.workspace}"
}

Thanks,

Do you happen to know if the TFC ENV variables can be accessed from within a sub-module referenced from a Private Module Registry ? I can access all the needed TFC_ env variables needed in my root module but not from within a sub-module.

Pass them as variables to your submodule?