2023-04-06 10:54:58 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"path/filepath"
|
|
|
|
|
2023-05-16 16:35:39 +00:00
|
|
|
"github.com/databricks/cli/bundle"
|
|
|
|
"github.com/databricks/cli/libs/cmdio"
|
|
|
|
"github.com/databricks/cli/libs/terraform"
|
2023-04-06 10:54:58 +00:00
|
|
|
"github.com/hashicorp/terraform-exec/tfexec"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PlanGoal string
|
|
|
|
|
|
|
|
var (
|
|
|
|
PlanDeploy = PlanGoal("deploy")
|
|
|
|
PlanDestroy = PlanGoal("destroy")
|
|
|
|
)
|
|
|
|
|
|
|
|
type plan struct {
|
|
|
|
goal PlanGoal
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *plan) Name() string {
|
|
|
|
return "terraform.Plan"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *plan) Apply(ctx context.Context, b *bundle.Bundle) ([]bundle.Mutator, error) {
|
|
|
|
tf := b.Terraform
|
|
|
|
if tf == nil {
|
|
|
|
return nil, fmt.Errorf("terraform not initialized")
|
|
|
|
}
|
|
|
|
|
2023-04-18 14:55:06 +00:00
|
|
|
cmdio.LogString(ctx, "Starting plan computation")
|
|
|
|
|
2023-04-06 10:54:58 +00:00
|
|
|
err := tf.Init(ctx, tfexec.Upgrade(true))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("terraform init: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Persist computed plan
|
|
|
|
tfDir, err := Dir(b)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
planPath := filepath.Join(tfDir, "plan")
|
|
|
|
destroy := p.goal == PlanDestroy
|
2023-04-18 14:55:06 +00:00
|
|
|
|
2023-04-06 10:54:58 +00:00
|
|
|
notEmpty, err := tf.Plan(ctx, tfexec.Destroy(destroy), tfexec.Out(planPath))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set plan in main bundle struct for downstream mutators
|
|
|
|
b.Plan = &terraform.Plan{
|
|
|
|
Path: planPath,
|
|
|
|
ConfirmApply: b.AutoApprove,
|
|
|
|
IsEmpty: !notEmpty,
|
|
|
|
}
|
2023-04-18 14:55:06 +00:00
|
|
|
|
|
|
|
cmdio.LogString(ctx, fmt.Sprintf("Planning complete and persisted at %s\n", planPath))
|
2023-04-06 10:54:58 +00:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Plan returns a [bundle.Mutator] that runs the equivalent of `terraform plan -out ./plan`
|
|
|
|
// from the bundle's ephemeral working directory for Terraform.
|
|
|
|
func Plan(goal PlanGoal) bundle.Mutator {
|
|
|
|
return &plan{
|
|
|
|
goal: goal,
|
|
|
|
}
|
|
|
|
}
|