Skip to content

TF_WORKSPACE not parsed for empty Cloud block #341

Open
@sergiorivera50

Description

@sergiorivera50

I have the following versions.tf

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

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:

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)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions