hashicorp / terraform-exec

Terraform CLI commands via Go.
https://pkg.go.dev/github.com/hashicorp/terraform-exec
Mozilla Public License 2.0
662 stars 112 forks source link

remove workspace env var and not set it to an empty string. #388

Closed bjhaid closed 1 year ago

bjhaid commented 1 year ago

Setting the environment variable to an empty string confuses the terraform binary as seen below:

TF_WORKSPACE= terraform init -no-color -input=false -get=false -upgrade=false -backend=false

Error: Terraform Cloud returned an unexpected error

invalid value for workspace

With this patch the TF_WORKSPACE will not exist and avoids the above problem. I have tested this locally with terraform 1.4.5 and it works.

hashicorp-cla commented 1 year ago

CLA assistant check
All committers have signed the CLA.

mrak commented 1 year ago

Some additional context: the current behavior (explicitly setting TF_WORKSPACE="") breaks tag-selected workspaces using Terraform Cloud such as this:

terraform {
  cloud {
    organization = "MyOrg"

    workspaces {
      tags = [
        "owner:my-team",
        "project:my-project",
      ]
    }
  }
}

Normally you'd use terraform workspace select to select the workspace, but terraform workspace cannot be used until terraform init has been run. In order for terraform init to run you need to either specify TF_WORKSPACE=my-workspace or you need to populate .terraform/environment.

The bug here is if TF_WORKSPACE is defined regardless of value terraform init skips any checking of .terraform/environment, including if the value of the env var is "".

By removing the TF_WORKSPACE env var instead of setting it to an empty string allows the automation pattern of using .terraform/environment to function as intended.

See the official HashiCorp help article Selecting a workspace when running Terraform in automation

bjhaid commented 1 year ago

@kmoe I fixed the tests can you help re-trigger the builds, thanks!

bjhaid commented 1 year ago

@kmoe looks like all checks have passed, how do we get this merged and released?

mrak commented 1 year ago

Any chance to get a release out with this change? Thanks!