hashicorp / hashicorp/terraform-exec

TF_WORKSPACE not parsed for empty Cloud block

Open
#341 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
786
Forks
129
PR merge metrics
No merged PRs in 30d

Description

I have the following `versions.tf`

```hcl

terraform {
cloud {} # source of the error
required_providers {
# something else
}
}
```

Note the empty cloud block; its fields should be parsed from the environment variables `TF_WORKSPACE` & `TF_CLOUD_ORGANIZATION`. Running the CLI myself, I manage to get it working.

I'm getting my environment variables from a dot env file using the following snippet of code
```go
err := godotenv.Load() // import "github.com/joho/godotenv"
if err != nil {
log.Fatal("Error loading .env file")
}
```

I have verified that I have correct access to the env variables after the previous statements are executed. But whenever I initialise terraform with `tf.Init(context.Background(), tfexec.Upgrade(true))`, it complains about not specifying a workspace (something that does not happen when using the CLI directly).

The interesting thing is, if I do manually specify TF variables in the HCL files, it all works. So it seems not to be a problem from not parsing environment variables but outright ignoring TF_WORKSPACE? Is this a possibility?

The following is my main, in case you need to see the entire code:

```go
package main

import (
"context"
"fmt"
"log"

"github.com/hashicorp/go-version"
"github.com/hashicorp/hc-install/product"
"github.com/hashicorp/hc-install/releases"
"github.com/hashicorp/terraform-exec/tfexec"
"github.com/joho/godotenv"
)

func main() {
const terraformDir = "terraform"

err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}

fmt.Println("Installing Terraform...")

installer := &releases.ExactVersion{
Product: product.Terraform,
Version: version.Must(version.NewVersion("1.2.0")),
}

execPath, err := installer.Install(context.Background())
if err != nil {
log.Fatalf("error installing Terraform: %s", err)
}

fmt.Println("Initializing Terraform project...")

tf, err := tfexec.NewTerraform(terraformDir, execPath)
if err != nil {
log.Fatalf("error running NewTerraform: %s", err)
}

// fmt.Println("Set TF_WORKSPACE")
// tf.SetEnv(map[string]string{
// "TF_WORKSPACE": "example-workspace",
// })

err = tf.Init(context.Background(), tfexec.Upgrade(true))
if err != nil {
log.Fatalf("error running Init: %s", err)
}

state, err := tf.Show(context.Background())
if err != nil {
log.Fatalf("error running Show: %s", err)
}

fmt.Println(state.FormatVersion) // "0.1"

err = tf.Apply(context.Background())
if err != nil {
log.Fatalf("error running Apply: %s", err)
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.