forked from nadnerb/terraform_exec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terraform_exec.go
255 lines (225 loc) · 6.95 KB
/
terraform_exec.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strings"
"github.com/codegangsta/cli"
"github.com/fatih/color"
"github.com/nadnerb/cli_command"
"github.com/nadnerb/terraform_config"
"github.com/nadnerb/terraform_exec/file"
"github.com/nadnerb/terraform_exec/security"
"github.com/nadnerb/terraform_exec/sync"
)
var cyan = color.New(color.FgCyan).SprintFunc()
var Bold = color.New(color.FgWhite, color.Bold)
var bold = Bold.SprintFunc()
var green = color.New(color.FgGreen).SprintFunc()
var red = color.New(color.FgRed).SprintFunc()
func main() {
app := cli.NewApp()
app.Name = "Terraform exec"
app.Usage = "Execute terraform commands across environments maintaining state in s3\nDefault project layout\n./<project>\n./config/<environment>"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "Show more output",
},
cli.BoolFlag{
Name: "e, env",
Usage: "Load AWS credentials from environment",
},
}
// Commands
app.Commands = []cli.Command{
{
Name: "run",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "no-sync",
Usage: "Don't perform initial s3 sync",
},
cli.StringFlag{
Name: "security",
Usage: "security provider, current options <default>, <aws-internal>",
},
cli.StringFlag{
Name: "security-role",
Usage: "security iam role if using -security=aws-internal security",
},
cli.StringFlag{
Name: "config-location",
Usage: "config location, must be format <location>/<environment>.tfvars",
},
},
Usage: "Run a terraform command (plan|apply|destroy|refresh)",
Action: CmdRun,
},
{
Name: "download",
Flags: []cli.Flag{
cli.StringFlag{
Name: "config-location",
Usage: "config location, must be format <location>/<environment>.tfvars",
},
},
Usage: "download existing state to s3",
Action: CmdDownload,
},
{
Name: "upload",
Flags: []cli.Flag{
cli.StringFlag{
Name: "config-location",
Usage: "config location, must be format <location>/<environment>.tfvars",
},
},
Usage: "upload existing state to s3",
Action: CmdUpload,
},
}
app.Run(os.Args)
}
var terraformCommands = map[string]TerraformCommand {
"plan": TerraformCommand{false, ""},
"apply": TerraformCommand{true, ""},
"refresh": TerraformCommand{true, ""},
"destroy": TerraformCommand{true, "-force"},
}
type TerraformCommand struct {
sync bool
extraArgs string
}
func CmdRun(c *cli.Context) {
if len(c.Args()) != 2 {
fmt.Printf("Incorrect usage\n")
fmt.Printf("run <terraform command> <environment>\n")
os.Exit(1)
}
IsTerraformProject()
terraformCommand := c.Args()[0]
environment := c.Args()[1]
security.Apply(c.String("security"), c)
IsSupportedTerraformCommand(terraformCommand)
fmt.Println()
fmt.Println("Run Terraform command")
fmt.Println("Command: ", bold(terraformCommand))
fmt.Println("Environment:", bold(environment))
fmt.Println()
configLocation := c.String("config-location")
config := terraform_config.LoadConfig(c.String("config-location"), environment)
if c.Bool("no-sync") {
red("SKIPPING S3 download of current state")
if command.InputAffirmative() {
red("Skipped syncing with S3")
} else {
DownloadState(config, environment)
}
} else {
DownloadState(config, environment)
}
tfVars := terraform_config.TerraformVars(configLocation, environment)
tfState := terraform_config.TerraformState(environment)
terraformActions := terraformCommands[terraformCommand]
// It would be great to use golang terraform so we don't have to install it separately
// I think we would need to use "github.com/mitchellh/cli" instead of current cli
cmdName := "terraform"
cmdArgs := []string{ terraformCommand, "-var-file", tfVars, fmt.Sprintf("-state=%s", tfState), "-var", fmt.Sprintf("environment=%s", environment) }
if terraformActions.extraArgs != "" {
cmdArgs = append(cmdArgs, terraformActions.extraArgs)
}
fmt.Println("---------------------------------------------")
Bold.Println(cmdName, strings.Join(cmdArgs, " "))
fmt.Println("---------------------------------------------")
fmt.Println()
command.Default().Execute(cmdName, cmdArgs)
fmt.Println()
fmt.Println("---------------------------------------------")
if terraformActions.sync {
fmt.Printf("S3 SYNC new changes\n")
UploadState(config, environment)
}
}
func CmdUpload(c *cli.Context) {
if len(c.Args()) != 1 {
fmt.Printf("Incorrect usage\n")
fmt.Printf("upload <environment>\n")
return
}
fmt.Println()
environment := c.Args()[0]
config := terraform_config.LoadConfig(c.String("config-location"), environment)
fmt.Println()
fmt.Println("Upload Terraform state")
fmt.Println("Environment:", bold(environment))
fmt.Println()
fmt.Printf("Upload current project state to s3\n")
if command.InputAffirmative() {
UploadState(config, environment)
} else {
color.Red("Aborted")
}
}
func UploadState(config *terraform_config.AwsConfig, environment string) {
tfState := terraform_config.TerraformState(environment)
s3Key := S3Key(config.S3_key, environment)
fmt.Printf("Uploading project state: %s to: %s/%s\n", green(tfState), green(config.S3_bucket), green(s3Key))
err := sync.Upload(config.Aws_region, config.S3_bucket, s3Key, tfState)
fmt.Println()
if err != nil {
command.Error("Failed to upload", err)
} else {
color.Green("Uploaded successfully to S3")
fmt.Println()
}
}
func CmdDownload(c *cli.Context) {
if len(c.Args()) != 1 {
fmt.Printf("Incorrect usage\n")
fmt.Printf("download <environment>\n")
return
}
environment := c.Args()[0]
fmt.Println()
fmt.Println("Download Terraform state")
fmt.Println("Environment:", bold(environment))
fmt.Println()
config := terraform_config.LoadConfig(c.String("config-location"), environment)
DownloadState(config, environment)
}
func DownloadState(config *terraform_config.AwsConfig, environment string) {
fmt.Println("Syncing project state with S3")
tfState := terraform_config.TerraformState(environment)
s3Key := S3Key(config.S3_key, environment)
fmt.Printf("Downloading project state: %s/%s to: %s\n", cyan(config.S3_bucket), cyan(s3Key), cyan(tfState))
err := sync.Download(config.Aws_region, config.S3_bucket, s3Key, tfState)
fmt.Println()
if err != nil {
command.Warn("Failed to download", err)
} else {
color.Green("Downloaded successfully from S3")
fmt.Println()
}
}
func S3Key(keyName string, environment string) string {
return fmt.Sprintf("%s/%s/terraform.tfstate", keyName, environment)
}
func IsTerraformProject() {
hasTfFiles, err := file.DirectoryContainsWithExtension(".", ".tf")
if err != nil && !hasTfFiles {
command.Error("No terraform files exist", err)
}
}
func IsSupportedTerraformCommand(terraformCommand string) {
if _, ok := terraformCommands[terraformCommand]; !ok {
fmt.Printf("Incorrect usage\n")
var buffer bytes.Buffer
buffer.WriteString("Valid commands: ")
for key := range terraformCommands {
buffer.WriteString(fmt.Sprintf("%s ", key))
}
command.Error("Incorrect run command", errors.New(buffer.String()))
}
}