-
Notifications
You must be signed in to change notification settings - Fork 8
/
tf_utils.go
77 lines (63 loc) · 1.76 KB
/
tf_utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package deleteutils
import (
"context"
"fmt"
"io"
"log"
"github.com/hashicorp/terraform-exec/tfexec"
"github.com/ministryofjustice/cloud-platform-cli/pkg/terraform"
)
type TFDataAccessLayer interface {
Init(context.Context, io.Writer) error
Plan(context.Context, io.Writer) (bool, error)
Destroy(context.Context, io.Writer) error
WorkspaceDelete(context.Context, string) error
}
func InitTfCLI(tf *terraform.TerraformCLIConfig, dryRun bool) (TFDataAccessLayer, error) {
if dryRun {
tf.PlanVars = append(tf.PlanVars, tfexec.Destroy(true))
}
terraform, err := terraform.NewTerraformCLI(tf)
if err != nil {
return nil, err
}
return terraform, nil
}
func terraformInit(tf TFDataAccessLayer, workingDir string) error {
// Start fresh and remove any local state.
if err := terraform.DeleteLocalState(workingDir, ".terraform", ".terraform.lock.hcl"); err != nil {
fmt.Println("Failed to delete local state, continuing anyway")
}
err := tf.Init(context.TODO(), log.Writer())
if err != nil {
return fmt.Errorf("failed to init terraform: %w", err)
}
return nil
}
func terraformDestroy(terraform TFDataAccessLayer, dryRun bool) error {
if dryRun {
if _, err := terraform.Plan(context.TODO(), log.Writer()); err != nil {
return fmt.Errorf("destroy plan terraform failed: %w", err)
}
} else {
if err := terraform.Destroy(context.TODO(), log.Writer()); err != nil {
return fmt.Errorf("failed to destroy terraform: %w", err)
}
}
return nil
}
func TerraformDestroyLayer(tf *terraform.TerraformCLIConfig, dryRun bool) error {
tfCli, err := InitTfCLI(tf, dryRun)
if err != nil {
return err
}
err = terraformInit(tfCli, tf.WorkingDir)
if err != nil {
return err
}
err = terraformDestroy(tfCli, dryRun)
if err != nil {
return err
}
return nil
}