hashicorp / terraform-exec

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

stderr is empty #374

Open veziak opened 1 year ago

veziak commented 1 year ago

Hi All, I'm trying to get what terraform writes to stdout and stderr and wrote the following code:

type StdWriter struct {
}
func (sw *StdWriter) Write(data []byte) (n int, err error) {
    s := string(data)
    print(s)
    return 0, nil
}

func main() {
    tf, err := tfexec.NewTerraform("./", "terraform")
    stdout := &StdWriter{}
    stderr := &StdWriter{}
    tf.SetStdout(stdout)
    tf.SetStderr(stderr)

    err = tf.Init(context.Background(), tfexec.Upgrade(true))
    if err != nil {
        print("terraform init failed.")
        print(err.Error())
    }
}

I tried to test it on a terraform code that should fail when 'terraform init' executed:

resource "ssss" "ssss" {
}

if I run 'terraform init' in terminal I get the following in stdout:

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/ssss...

and in stderr:

│ Error: Failed to query available provider packages
│ 
│ Could not retrieve the list of available versions for provider
│ hashicorp/ssss: provider registry registry.terraform.io does not have a
│ provider named registry.terraform.io/hashicorp/ssss

If I try to run terraform with terraform-exec I get stdout printed as expected, but stderr is empty. If I change tf.SetStderr(stderr) to tf.SetStderr(os.Stderr) then I can see stderr printed. Do I miss something or stderr can be written only to os.Stderr ?

kmoe commented 1 year ago

Just to check, are you on tfexec v0.18.1? There was a bug in this functionality in v0.18.0.

veziak commented 1 year ago

yep, I've seen that issue and double checked the version, it's v0.18.1

veziak commented 1 year ago

and terraform version: Terraform v1.4.1 on linux_amd64

sasikeda commented 1 year ago

Thank you for raising the issue. I am also facing the same problem using tf.Destroy, I am using v0.19.0. Any workaround you could recommend ?

veziak commented 1 year ago

Thank you for raising the issue. I am also facing the same problem, I am using v0.19.0. Any workaround you could recommend ?

in my case it was easier to work with "os/exec" directly without terraform-exec