forked from cloudfoundry/bosh-bootloader
/
terraform.go
90 lines (74 loc) · 1.9 KB
/
terraform.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
78
79
80
81
82
83
84
85
86
87
88
89
90
package actors
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
integration "github.com/cloudfoundry/bosh-bootloader/integration-test"
. "github.com/onsi/ginkgo"
)
const (
template = `variable "project_id" {
type = "string"
}
variable "region" {
type = "string"
}
variable "zone" {
type = "string"
}
variable "env_id" {
type = "string"
}
variable "credentials" {
type = "string"
}
provider "google" {
credentials = "${file("${var.credentials}")}"
project = "${var.project_id}"
region = "${var.region}"
}`
)
type Terraform struct {
projectID string
region string
zone string
serviceAccountKeyPath string
}
func NewTerraform(config integration.Config) Terraform {
return Terraform{
projectID: config.GCPProjectID,
region: config.GCPRegion,
zone: config.GCPZone,
serviceAccountKeyPath: config.GCPServiceAccountKeyPath,
}
}
func (t Terraform) Destroy(state integration.State) error {
tempDir, err := ioutil.TempDir("", "")
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(tempDir, "terraform.tfstate"), []byte(state.TFState()), os.ModePerm)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(tempDir, "template.tf"), []byte(template), os.ModePerm)
if err != nil {
return err
}
args := []string{"destroy", "-force"}
args = append(args, makeVar("project_id", t.projectID)...)
args = append(args, makeVar("env_id", state.EnvID())...)
args = append(args, makeVar("region", t.region)...)
args = append(args, makeVar("zone", t.zone)...)
args = append(args, makeVar("credentials", t.serviceAccountKeyPath)...)
runCommand := exec.Command("terraform", args...)
runCommand.Dir = tempDir
runCommand.Stdout = GinkgoWriter
runCommand.Stderr = GinkgoWriter
return runCommand.Run()
}
func makeVar(name string, value string) []string {
return []string{"-var", fmt.Sprintf("%s=%s", name, value)}
}