I’m trying to use Terraform Cloud with the cloud block, but I need to set the workspace name dynamically depending on the environment: dev or prod.
Like this:
terraform {
cloud {
organization = "my-org"
workspaces {
name = "my-workspace-${var.env}" // <- Not allowed
}
}
}
Unfortunately, variables are not allowed in the cloud block, so I am stuck .
I could write a script to generate main terraform file with a hard-coded workspace name but that seems ridiculous.
Why is it so hard to do such a simple thing as choose the workspace programmatically? How can I get around this?
Thank you
Hi @david-wb,
The intended design here is for you to add tags to your workspaces and then use the tags
argument instead of the name
argument. For example, if you add a tag my-workspace
to both workspaces (which I assume in practice is more like a component/subsystem/application name in your system) then you can specify that this configuration applies to both by specifying that tag:
terraform {
cloud {
organization = "my-org"
workspaces {
tags = ["my-workspace"]
}
}
}
If you have added that tag to both the my-workspace-dev
and my-workspace-prod
workspaces then terraform workspace list
should show them both, and terraform workspace select
should allow you to choose between them.
But this is running in a CI environment @apparentlymart. I need a way to do it programmatically in an automated fashion without manually selecting anything.
Using a script to generate a tf file with the workspace name hard coded works just fine, but it’s ugly.
Hey @david-wb,
The environment variable TF_WORKSPACE
should be respected, allowing you to programmatically select the workspace name. That’s documented here. Can you try that and let us know if it does not?
Thanks!
Hey guys. This assumes that my-workspace-dev
and my-workspace-prod
already exist in Terraform Cloud, correct? For my use case, I need to create new dynamic terraform cloud workspaces using a CLI-driven workflow in a CI/CD pipeline. Is there a way to do that?
According to the docs
Terraform Cloud will not create a new workspace from this variable; the workspace must exist in the specified organization.
Any idea for proposed solution to create dynamic workspace names in HCP cloud