Refactor Provisioner to distinguish Plan and Apply (#5036)

This commit is contained in:
Ammar Bandukwala
2022-11-11 16:45:58 -06:00
committed by GitHub
parent 71601f4971
commit 95fb59696e
37 changed files with 942 additions and 648 deletions

View File

@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
@ -76,6 +77,10 @@ func (e executor) execWriteOutput(ctx, killCtx context.Context, args, env []stri
// #nosec
cmd := exec.CommandContext(killCtx, e.binaryPath, args...)
cmd.Dir = e.workdir
if env == nil {
// We don't want to passthrough host env when unset.
env = []string{}
}
cmd.Env = env
// We want logs to be written in the correct order, so we wrap all logging
@ -238,10 +243,15 @@ func (e executor) plan(ctx, killCtx context.Context, env, vars []string, logr lo
if err != nil {
return nil, err
}
planFileByt, err := os.ReadFile(planfilePath)
if err != nil {
return nil, err
}
return &proto.Provision_Response{
Type: &proto.Provision_Response_Complete{
Complete: &proto.Provision_Complete{
Resources: resources,
Plan: planFileByt,
},
},
}, nil
@ -292,21 +302,26 @@ func (e executor) graph(ctx, killCtx context.Context) (string, error) {
}
// revive:disable-next-line:flag-parameter
func (e executor) apply(ctx, killCtx context.Context, env, vars []string, logr logSink, destroy bool,
func (e executor) apply(
ctx, killCtx context.Context, plan []byte, env []string, logr logSink,
) (*proto.Provision_Response, error) {
planFile, err := ioutil.TempFile("", "coder-terrafrom-plan")
if err != nil {
return nil, xerrors.Errorf("create plan file: %w", err)
}
_, err = planFile.Write(plan)
if err != nil {
return nil, xerrors.Errorf("write plan file: %w", err)
}
defer os.Remove(planFile.Name())
args := []string{
"apply",
"-no-color",
"-auto-approve",
"-input=false",
"-json",
"-refresh=true",
}
if destroy {
args = append(args, "-destroy")
}
for _, variable := range vars {
args = append(args, "-var", variable)
planFile.Name(),
}
outWriter, doneOut := provisionLogWriter(logr)
@ -318,7 +333,7 @@ func (e executor) apply(ctx, killCtx context.Context, env, vars []string, logr l
<-doneErr
}()
err := e.execWriteOutput(ctx, killCtx, args, env, outWriter, errWriter)
err = e.execWriteOutput(ctx, killCtx, args, env, outWriter, errWriter)
if err != nil {
return nil, xerrors.Errorf("terraform apply: %w", err)
}