'Create new workspace in Terraform Cloud without any existing workspace through CLI

I'm setting up ephemeral review environments on GitLab MRs through Terraform and GitLab CI. I use Terraform Cloud as a backend. I want to create a workspace for each of the review env and do it dynamically based on some environment variables in GitLab CI.

My problem is that I cannot create a new Terraform Cloud workspace through the CLI without having an existing workspace first. It seems counterintuitive since I have no use of that workspace. If a workspace exist I can run terraform init, then terraform workspace new and the workspace is created in Terraform Cloud. If I don't create a workspace first init doesn't work as no workspace exist and if I want to run terraform workspace new before it yells because init hasn't been run first. My configuration is:

terraform {
  cloud {
    organization = "my-org"

    workspaces {
      tags = ["review", "customer:test-frontend"]
    }
  }
}

I know I can create a workspace first through the API but that's cumbersome. I tried using TF_WORKSPACE but it should point to an existing workspace which is not my case. My current solution is switching to:

terraform {
  cloud {
    organization = "my-org"

    workspaces {
      name = "<TF_WORKSPACE>"
    }
  }
}

Using sed to replace that token with the dynamic name before calling terraform init.

Is there a way to do it through the CLI? Am I missing something here?



Solution 1:[1]

I think you are confusing Terraform Cloud workspaces with Terraform CLI workspaces.

Note: Terraform Cloud and Terraform CLI both have features called "workspaces," but they're slightly different. Terraform Cloud's workspaces behave more like completely separate working directories.

https://www.terraform.io/cli/workspaces

When using Terraform Cloud, a Terraform Cloud workspace is required. The usage of Terraform CLI workspaces is optional.

https://www.terraform.io/cloud-docs/workspaces#terraform-cloud-vs-terraform-cli-workspaces

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tgebauer