Files
atlantis/server/pre_run.go
Luke Kysow d425de95fa Refactoring
* set version in one place
* rename ExecutionContext to CommandContext
* delete unneeded PullRequestContext since it just duplicated what is in CommandContext
* split fields inside CommandContext into Repo, PullRequest, and User models
* clean up unused fields
* remove base_executor stuff which was trying to do inheritance in go and didn't get us anywhere
* clean up unused code and assets
* created a locking.Client that creates the Keys that are used on the front-end. This allows the backends to store the locks any way they like as long as they support the interface
2017-06-17 14:14:21 -07:00

101 lines
2.4 KiB
Go

package server
import (
"bufio"
"fmt"
"github.com/hootsuite/atlantis/logging"
"io/ioutil"
"os"
"os/exec"
)
const InlineShebang = "/bin/sh -e"
// todo: make OO
// PreRun is a function that will determine whether
func PreRun(c *Config, log *logging.SimpleLogger, path string, command *Command) error {
log.Info("Staring pre run in %s", path)
var execScript string
if command.commandType == Plan {
// we create a script from the commands provided
s, err := createScript(c.PrePlan.Commands)
if err != nil {
return err
}
execScript = s
}
if command.commandType == Apply {
// we create a script from the commands provided
s, err := createScript(c.PreApply.Commands)
if err != nil {
return err
}
execScript = s
}
if execScript != "" {
defer os.Remove(execScript)
log.Info("Running script %s", execScript)
// set environment variable for the run.
// this is to support scripts to use the ENVIRONMENT and WORKSPACE variables in their scripts
if command.environment != "" {
os.Setenv("ENVIRONMENT", command.environment)
}
if c.TerraformVersion != "" {
os.Setenv("ATLANTIS_TERRAFORM_VERSION", c.TerraformVersion)
}
os.Setenv("WORKSPACE", path)
output, err := execute(execScript)
if err != nil {
return err
}
log.Info("output: \n%s", output)
}
return nil
}
func createScript(cmds []string) (string, error) {
var scriptName string
if cmds != nil {
tmp, err := ioutil.TempFile("/tmp", "atlantis-temp-script")
if err != nil {
return "", fmt.Errorf("Error preparing shell script: %s", err)
}
scriptName = tmp.Name()
// Write our contents to it
writer := bufio.NewWriter(tmp)
writer.WriteString(fmt.Sprintf("#!%s\n", InlineShebang))
for _, command := range cmds {
if _, err := writer.WriteString(command + "\n"); err != nil {
return "", fmt.Errorf("Error preparing script: %s", err)
}
}
if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error flushing file when preparing script: %s", err)
}
tmp.Close()
}
return scriptName, nil
}
func execute(script string) (string, error) {
if _, err := os.Stat(script); err == nil {
os.Chmod(script, 0775)
}
localCmd := exec.Command("sh", "-c", script)
out, err := localCmd.CombinedOutput()
output := string(out)
if err != nil {
return output, fmt.Errorf("Error running script %s: %v %s", script, err, output)
}
return output, nil
}