0
0
mirror of https://github.com/thegeeklab/wp-opentofu.git synced 2024-11-13 23:40:39 +00:00
wp-opentofu/main.go

126 lines
2.4 KiB
Go
Raw Normal View History

2015-11-09 19:23:42 +00:00
package main
import (
"fmt"
"os"
"os/exec"
"strings"
2016-02-09 19:27:12 +00:00
"io/ioutil"
2015-11-09 19:23:42 +00:00
"github.com/drone/drone-plugin-go/plugin"
)
type terraform struct {
Remote remote `json:"remote"`
Plan bool `json:"plan"`
Vars map[string]string `json:"vars"`
Cacert string `json:"ca_cert"`
Sensitive bool `json:"sensitive"`
}
type remote struct {
Backend string `json:"backend"`
Config map[string]string `json:"config"`
2015-11-09 19:23:42 +00:00
}
func main() {
workspace := plugin.Workspace{}
vargs := terraform{}
2015-11-09 19:23:42 +00:00
plugin.Param("workspace", &workspace)
plugin.Param("vargs", &vargs)
plugin.MustParse()
var commands []*exec.Cmd
remote := vargs.Remote
if vargs.Cacert != "" {
commands = append(commands, installCaCert(vargs.Cacert))
2016-02-09 19:27:12 +00:00
}
if remote.Backend != "" {
commands = append(commands, deleteCache())
commands = append(commands, remoteConfigCommand(remote))
}
commands = append(commands, planCommand(vargs.Vars))
2016-02-14 22:00:32 +00:00
if !vargs.Plan {
commands = append(commands, applyCommand())
2015-11-09 19:23:42 +00:00
}
commands = append(commands, deleteCache())
2015-11-09 19:23:42 +00:00
for _, c := range commands {
c.Env = os.Environ()
c.Dir = workspace.Path
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if !vargs.Sensitive {
trace(c)
}
2015-11-09 19:23:42 +00:00
err := c.Run()
2015-11-09 19:23:42 +00:00
if err != nil {
2015-11-10 13:56:18 +00:00
fmt.Println("Error!")
fmt.Println(err)
2015-11-09 19:23:42 +00:00
os.Exit(1)
}
2015-11-10 13:56:18 +00:00
fmt.Println("Command completed successfully")
2015-11-09 19:23:42 +00:00
}
}
2016-02-09 19:27:12 +00:00
func installCaCert(cacert string) *exec.Cmd {
ioutil.WriteFile("/usr/local/share/ca-certificates/ca_cert.crt", []byte(cacert), 0644)
return exec.Command(
"update-ca-certificates",
)
}
func deleteCache() *exec.Cmd {
return exec.Command(
"rm",
"-rf",
".terraform",
)
}
func remoteConfigCommand(config remote) *exec.Cmd {
args := []string{
"remote",
"config",
fmt.Sprintf("-backend=%s", config.Backend),
}
for k, v := range config.Config {
args = append(args, fmt.Sprintf("-backend-config=%s=%s", k, v))
}
return exec.Command(
"terraform",
args...,
)
}
func planCommand(variables map[string]string) *exec.Cmd {
args := []string{
"plan",
"-out=plan.tfout",
}
for k, v := range variables {
args = append(args, "-var")
args = append(args, fmt.Sprintf("%s=%s", k, v))
}
return exec.Command(
"terraform",
args...,
)
}
func applyCommand() *exec.Cmd {
return exec.Command(
"terraform",
"apply",
"plan.tfout",
)
2015-11-09 19:23:42 +00:00
}
func trace(cmd *exec.Cmd) {
fmt.Println("$", strings.Join(cmd.Args, " "))
}