obm/internal/terraform/terraform.go

51 lines
1.1 KiB
Go

// Package terraform wraps Terraform operations (init, plan, apply, destroy).
package terraform
import (
"fmt"
"os/exec"
)
// Runner executes Terraform commands.
type Runner struct {
WorkDir string
}
// NewRunner creates a Terraform runner for the given working directory.
func NewRunner(workDir string) *Runner {
return &Runner{WorkDir: workDir}
}
// Init runs terraform init.
func (r *Runner) Init() error {
return r.run("init", "-input=false")
}
// Plan runs terraform plan.
func (r *Runner) Plan(destroy bool) error {
args := []string{"plan"}
if destroy {
args = append(args, "-destroy")
}
return r.run(args...)
}
// Apply runs terraform apply.
func (r *Runner) Apply() error {
return r.run("apply", "-auto-approve")
}
// Destroy runs terraform destroy.
func (r *Runner) Destroy() error {
return r.run("destroy", "-auto-approve")
}
func (r *Runner) run(args ...string) error {
cmd := exec.Command("terraform", args...)
cmd.Dir = r.WorkDir
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("terraform %v: %w\n%s", args, err, output)
}
return nil
}