-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
218 lines (196 loc) · 7.15 KB
/
helper.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"bytes"
"context"
"flag"
"fmt"
"github.com/hashicorp/go-version"
"github.com/hashicorp/hc-install/product"
"github.com/hashicorp/hc-install/releases"
"github.com/hashicorp/terraform-exec/tfexec"
"log"
"os"
"os/exec"
)
var awsAccountNumber = flag.Uint("account-number", 0, "Account number of AWS deployment target")
var environment = flag.String("environment", "", "Target environment = prod, nonprod, etc")
var awsRegion = flag.String("region", "us-east-1", "Target region: e.g. us-east-1, eu-west-1")
var appName = flag.String("app-name", "example-service", "Application name: e.g. jwt-authorizer")
var tfOp = flag.String("tfop", "", "Terraform operation = init|plan|apply|destroy")
var opConfirmed = flag.Bool("confirm", false, "For destructive operations this should be set to true rather than false")
var build = flag.String("build", "all", "When running tfop plan or apply, which Lambda functions to build: all, none, <name-of-lambda>")
func main() {
flag.Parse()
if tfOperationIsDestructiveYetUnconfirmed() {
log.Printf("******** destructive Terraform operation %s chosen by not confirmed will run plan instead ********\n", *tfOp)
}
if shouldBuildLambdas() {
buildLambdas()
}
if thereIsATfOperationToPerform() {
runTerraformCommandForRegion(*awsRegion)
}
}
func thereIsATfOperationToPerform() bool {
return *tfOp != "skip"
}
func tfOperationIsDestructiveYetUnconfirmed() bool {
return !*opConfirmed && (*tfOp == "apply" || *tfOp == "destroy")
}
func runTerraformCommandForRegion(awsRegion string) {
tf := setupTerraformExec(context.Background())
var buf bytes.Buffer
tf.SetStdout(&buf)
tfWorkingBucket := fmt.Sprintf("%d-%s-terraform-deployments", *awsAccountNumber, awsRegion)
switch *tfOp {
case "init":
terraformInit(tf, tfWorkingBucket, awsRegion)
case "plan":
terraformPlan(tf, tfWorkingBucket, *awsAccountNumber, *environment, false)
case "apply":
if *opConfirmed {
terraformApply(tf, tfWorkingBucket, *awsAccountNumber, *environment)
} else {
log.Println("destructive apply not confirmed running plan instead...")
terraformPlan(tf, tfWorkingBucket, *awsAccountNumber, *environment, false)
}
case "destroy":
if *opConfirmed {
terraformDestroy(tf, tfWorkingBucket, *awsAccountNumber, *environment)
} else {
log.Println("destructive destroy not confirmed running plan destroy instead...")
terraformPlan(tf, tfWorkingBucket, *awsAccountNumber, *environment, true)
}
default:
log.Fatalf("Bad operation: --tfop should be one of init, plan, apply, skip, or destroy")
}
log.Println(buf.String())
}
func shouldBuildLambdas() bool {
return *build != "none" && (*tfOp == "plan" || *tfOp == "apply" || *tfOp == "skip")
}
func setupTerraformExec(ctx context.Context) *tfexec.Terraform {
log.Println("installing Terraform...")
installer := &releases.ExactVersion{
Product: product.Terraform,
Version: version.Must(version.NewVersion("1.6")),
}
execPath, err := installer.Install(ctx)
if err != nil {
log.Fatalf("error installing Terraform: %s", err)
}
workingDir := "terraform"
tf, err := tfexec.NewTerraform(workingDir, execPath)
if err != nil {
log.Fatalf("error running NewTerraform: %s", err)
}
return tf
}
func terraformInit(tf *tfexec.Terraform, tfWorkingBucket string, awsRegion string) {
remoteStateFile := fmt.Sprintf("key=tfstate/%s/%s.json", *environment, *appName)
log.Println("initialising Terraform using remote state file ", remoteStateFile)
if err := tf.Init(context.Background(),
tfexec.Upgrade(true),
tfexec.BackendConfig(remoteStateFile),
tfexec.BackendConfig(fmt.Sprintf("bucket=%s", tfWorkingBucket)),
tfexec.BackendConfig(fmt.Sprintf("region=%s", awsRegion))); err != nil {
log.Fatalf("error running Init: %s", err)
}
}
func terraformPlan(tf *tfexec.Terraform, tfWorkingBucket string, awsAccountNumber uint, environment string, destroyFlag bool) {
if destroyFlag {
log.Println("planning Terraform destroy...")
} else {
log.Println("planning Terraform apply...")
}
_, err := tf.Plan(context.Background(),
tfexec.Refresh(true),
tfexec.Destroy(destroyFlag),
tfexec.Var(fmt.Sprintf("terraform_working_bucket=%s", tfWorkingBucket)),
tfexec.Var(fmt.Sprintf("account_number=%d", awsAccountNumber)),
tfexec.Var(fmt.Sprintf("environment=%s", environment)),
tfexec.Var(fmt.Sprintf("product=%s", *appName)),
tfexec.VarFile(fmt.Sprintf("environments/%s.tfvars", environment)),
)
if err != nil {
log.Fatalf("error running Plan: %s", err)
}
}
func terraformApply(tf *tfexec.Terraform, workingBucket string, awsAccountNumber uint, environment string) {
log.Println("applying Terraform...")
if err := tf.Apply(context.Background(),
tfexec.Refresh(true),
tfexec.Var(fmt.Sprintf("terraform_working_bucket=%s", workingBucket)),
tfexec.Var(fmt.Sprintf("account_number=%d", awsAccountNumber)),
tfexec.Var(fmt.Sprintf("environment=%s", environment)),
tfexec.Var(fmt.Sprintf("product=%s", *appName)),
tfexec.VarFile(fmt.Sprintf("environments/%s.tfvars", environment)),
); err != nil {
log.Fatalf("error running Apply: %s", err)
}
displayTerraformOutputs(tf)
}
func terraformDestroy(tf *tfexec.Terraform, workingBucket string, awsAccountNumber uint, environment string) {
log.Println("destroying all the things...")
if err := tf.Destroy(context.Background(),
tfexec.Refresh(true),
tfexec.Var(fmt.Sprintf("terraform_working_bucket=%s", workingBucket)),
tfexec.Var(fmt.Sprintf("account_number=%d", awsAccountNumber)),
tfexec.Var(fmt.Sprintf("environment=%s", environment)),
tfexec.VarFile(fmt.Sprintf("environments/%s.tfvars", environment)),
); err != nil {
log.Fatalf("error running Destroy: %s", err)
}
displayTerraformOutputs(tf)
}
func displayTerraformOutputs(tf *tfexec.Terraform) {
outputs, err := tf.Output(context.Background())
if err != nil {
log.Fatalf("Error outputting outputs: %v", err)
}
if len(outputs) > 0 {
fmt.Println("Terraform outputs:")
}
for key := range outputs {
if outputs[key].Sensitive {
continue
}
fmt.Println(fmt.Sprintf("%s = %s\n", key, string(outputs[key].Value)))
}
}
func buildLambdas() {
log.Println("building Lambdas...")
if *build == "all" {
lambdas, err := os.ReadDir("lambdas")
if err != nil {
fmt.Println("Error:", err)
return
}
for _, lambda := range lambdas {
if lambda.Name() == "common" { // this allows you to have common code between your Lambdas
continue
}
buildLambda(lambda.Name())
}
} else {
buildLambda(*build)
}
}
func buildLambda(lambdaName string) {
log.Printf("running unit tests for %s Lambda...\n", lambdaName)
runCmdIn(fmt.Sprintf("lambdas/%s", lambdaName), "make", "unit-test")
log.Printf("building %s Lambda...\n", lambdaName)
runCmdIn(fmt.Sprintf("lambdas/%s", lambdaName), "make", "build")
log.Printf("running integration tests for %s Lambda...\n", lambdaName)
runCmdIn(fmt.Sprintf("lambdas/%s", lambdaName), "make", "int-test")
log.Printf("building %s Lambda for AWS...\n", lambdaName)
runCmdIn(fmt.Sprintf("lambdas/%s", lambdaName), "make", "target")
}
func runCmdIn(dir string, command string, args ...string) *exec.Cmd {
cmd := exec.Command(command, args...)
cmd.Dir = dir
if err := cmd.Run(); err != nil {
log.Fatalf("error running %s %s: %s", command, args, err)
}
return cmd
}