The library provides programmatic access to Terraform CLI commands. Commands like Init or Show are called with a context.Context. Some commands accept functional options (e.g., tfexec.Upgrade(true)) to modify behavior.
Example workflow:
- Initialize the
tfexec.Terraform instance. - Run
tf.Init to initialize the working directory. - Run commands like
tf.Show to retrieve structured state data.
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"
)
func main() {
installer := &releases.ExactVersion{
Product: product.Terraform,
Version: version.Must(version.NewVersion("1.0.6")),
}
execPath, err := installer.Install(context.Background())
if err != nil {
log.Fatalf("error installing Terraform: %s", err)
}
workingDir := "/path/to/working/dir"
tf, err := tfexec.NewTerraform(workingDir, execPath)
if err != nil {
log.Fatalf("error running NewTerraform: %s", err)
}
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"
}