rewrite remote-exec as an internal provisioner

This commit is contained in:
James Bardin 2020-11-25 14:06:32 -05:00
parent d130add682
commit 1ec8d921d4
2 changed files with 186 additions and 157 deletions

View File

@ -3,92 +3,135 @@ package remoteexec
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"strings" "strings"
"time" "sync"
"github.com/hashicorp/terraform/communicator" "github.com/hashicorp/terraform/communicator"
"github.com/hashicorp/terraform/communicator/remote" "github.com/hashicorp/terraform/communicator/remote"
"github.com/hashicorp/terraform/internal/legacy/helper/schema" "github.com/hashicorp/terraform/configs/configschema"
"github.com/hashicorp/terraform/internal/legacy/terraform" "github.com/hashicorp/terraform/provisioners"
"github.com/mitchellh/go-linereader" "github.com/mitchellh/go-linereader"
"github.com/zclconf/go-cty/cty"
) )
// maxBackoffDealy is the maximum delay between retry attempts func New() provisioners.Interface {
var maxBackoffDelay = 10 * time.Second return &provisioner{}
var initialBackoffDelay = time.Second
func Provisioner() terraform.ResourceProvisioner {
return &schema.Provisioner{
Schema: map[string]*schema.Schema{
"inline": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
PromoteSingle: true,
Optional: true,
ConflictsWith: []string{"script", "scripts"},
},
"script": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"inline", "scripts"},
},
"scripts": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
ConflictsWith: []string{"script", "inline"},
},
},
ApplyFunc: applyFn,
}
} }
// Apply executes the remote exec provisioner type provisioner struct {
func applyFn(ctx context.Context) error { // this stored from the running context, so that Stop() can cancel the
connState := ctx.Value(schema.ProvRawStateKey).(*terraform.InstanceState) // command
data := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData) mu sync.Mutex
o := ctx.Value(schema.ProvOutputKey).(terraform.UIOutput) cancel context.CancelFunc
}
// Get a new communicator func (p *provisioner) GetSchema() (resp provisioners.GetSchemaResponse) {
comm, err := communicator.New(connState) schema := &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"inline": {
Type: cty.List(cty.String),
Optional: true,
},
"script": {
Type: cty.String,
Optional: true,
},
"scripts": {
Type: cty.List(cty.String),
Optional: true,
},
},
}
resp.Provisioner = schema
return resp
}
func (p *provisioner) ValidateProvisionerConfig(req provisioners.ValidateProvisionerConfigRequest) (resp provisioners.ValidateProvisionerConfigResponse) {
cfg, err := p.GetSchema().Provisioner.CoerceValue(req.Config)
if err != nil { if err != nil {
return err resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
}
inline := cfg.GetAttr("inline")
script := cfg.GetAttr("script")
scripts := cfg.GetAttr("scripts")
set := 0
if !inline.IsNull() {
set++
}
if !script.IsNull() {
set++
}
if !scripts.IsNull() {
set++
}
if set != 1 {
resp.Diagnostics = resp.Diagnostics.Append(errors.New(
`only one of "inline", "script", or "scripts" must be set`))
}
return resp
}
func (p *provisioner) ProvisionResource(req provisioners.ProvisionResourceRequest) (resp provisioners.ProvisionResourceResponse) {
p.mu.Lock()
ctx, cancel := context.WithCancel(context.Background())
p.cancel = cancel
p.mu.Unlock()
comm, err := communicator.New(req.Connection)
if err != nil {
resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
} }
// Collect the scripts // Collect the scripts
scripts, err := collectScripts(data) scripts, err := collectScripts(req.Config)
if err != nil { if err != nil {
return err resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
} }
for _, s := range scripts { for _, s := range scripts {
defer s.Close() defer s.Close()
} }
// Copy and execute each script // Copy and execute each script
if err := runScripts(ctx, o, comm, scripts); err != nil { if err := runScripts(ctx, req.UIOutput, comm, scripts); err != nil {
return err resp.Diagnostics = resp.Diagnostics.Append(err)
return resp
} }
return resp
}
func (p *provisioner) Stop() error {
p.mu.Lock()
defer p.mu.Unlock()
p.cancel()
return nil
}
func (p *provisioner) Close() error {
return nil return nil
} }
// generateScripts takes the configuration and creates a script from each inline config // generateScripts takes the configuration and creates a script from each inline config
func generateScripts(d *schema.ResourceData) ([]string, error) { func generateScripts(inline cty.Value) ([]string, error) {
var lines []string var lines []string
for _, l := range d.Get("inline").([]interface{}) { for _, l := range inline.AsValueSlice() {
line, ok := l.(string) s := l.AsString()
if !ok { if s == "" {
return nil, fmt.Errorf("Error parsing %v as a string", l) return nil, errors.New("invalid empty string in 'scripts'")
} }
lines = append(lines, line) lines = append(lines, s)
} }
lines = append(lines, "") lines = append(lines, "")
@ -97,10 +140,10 @@ func generateScripts(d *schema.ResourceData) ([]string, error) {
// collectScripts is used to collect all the scripts we need // collectScripts is used to collect all the scripts we need
// to execute in preparation for copying them. // to execute in preparation for copying them.
func collectScripts(d *schema.ResourceData) ([]io.ReadCloser, error) { func collectScripts(v cty.Value) ([]io.ReadCloser, error) {
// Check if inline // Check if inline
if _, ok := d.GetOk("inline"); ok { if inline := v.GetAttr("inline"); !inline.IsNull() {
scripts, err := generateScripts(d) scripts, err := generateScripts(inline)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -115,21 +158,21 @@ func collectScripts(d *schema.ResourceData) ([]io.ReadCloser, error) {
// Collect scripts // Collect scripts
var scripts []string var scripts []string
if script, ok := d.GetOk("script"); ok { if script := v.GetAttr("script"); !script.IsNull() {
scr, ok := script.(string) s := script.AsString()
if !ok { if s == "" {
return nil, fmt.Errorf("Error parsing script %v as string", script) return nil, errors.New("invalid empty string in 'script'")
} }
scripts = append(scripts, scr) scripts = append(scripts, s)
} }
if scriptList, ok := d.GetOk("scripts"); ok { if scriptList := v.GetAttr("scripts"); !scriptList.IsNull() {
for _, script := range scriptList.([]interface{}) { for _, script := range scriptList.AsValueSlice() {
scr, ok := script.(string) s := script.AsString()
if !ok { if s == "" {
return nil, fmt.Errorf("Error parsing script %v as string", script) return nil, errors.New("invalid empty string in 'script'")
} }
scripts = append(scripts, scr) scripts = append(scripts, script.AsString())
} }
} }
@ -151,12 +194,7 @@ func collectScripts(d *schema.ResourceData) ([]io.ReadCloser, error) {
} }
// runScripts is used to copy and execute a set of scripts // runScripts is used to copy and execute a set of scripts
func runScripts( func runScripts(ctx context.Context, o provisioners.UIOutput, comm communicator.Communicator, scripts []io.ReadCloser) error {
ctx context.Context,
o terraform.UIOutput,
comm communicator.Communicator,
scripts []io.ReadCloser) error {
retryCtx, cancel := context.WithTimeout(ctx, comm.Timeout()) retryCtx, cancel := context.WithTimeout(ctx, comm.Timeout())
defer cancel() defer cancel()
@ -182,8 +220,8 @@ func runScripts(
defer outW.Close() defer outW.Close()
defer errW.Close() defer errW.Close()
go copyOutput(o, outR) go copyUIOutput(o, outR)
go copyOutput(o, errR) go copyUIOutput(o, errR)
remotePath := comm.ScriptPath() remotePath := comm.ScriptPath()
@ -216,8 +254,7 @@ func runScripts(
return nil return nil
} }
func copyOutput( func copyUIOutput(o provisioners.UIOutput, r io.Reader) {
o terraform.UIOutput, r io.Reader) {
lr := linereader.New(r) lr := linereader.New(r)
for line := range lr.Ch { for line := range lr.Ch {
o.Output(line) o.Output(line)

View File

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"log"
"testing" "testing"
"time" "time"
@ -11,44 +12,34 @@ import (
"github.com/hashicorp/terraform/communicator" "github.com/hashicorp/terraform/communicator"
"github.com/hashicorp/terraform/communicator/remote" "github.com/hashicorp/terraform/communicator/remote"
"github.com/hashicorp/terraform/internal/legacy/helper/schema"
"github.com/hashicorp/terraform/internal/legacy/terraform" "github.com/hashicorp/terraform/internal/legacy/terraform"
"github.com/hashicorp/terraform/provisioners"
"github.com/mitchellh/cli"
"github.com/zclconf/go-cty/cty"
) )
func TestResourceProvisioner_impl(t *testing.T) {
var _ terraform.ResourceProvisioner = Provisioner()
}
func TestProvisioner(t *testing.T) {
if err := Provisioner().(*schema.Provisioner).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestResourceProvider_Validate_good(t *testing.T) { func TestResourceProvider_Validate_good(t *testing.T) {
c := testConfig(t, map[string]interface{}{ c := cty.ObjectVal(map[string]cty.Value{
"inline": "echo foo", "inline": cty.ListVal([]cty.Value{cty.StringVal("echo foo")}),
}) })
warn, errs := Provisioner().Validate(c) resp := New().ValidateProvisionerConfig(provisioners.ValidateProvisionerConfigRequest{
if len(warn) > 0 { Config: c,
t.Fatalf("Warnings: %v", warn) })
} if len(resp.Diagnostics) > 0 {
if len(errs) > 0 { t.Fatal(resp.Diagnostics.ErrWithWarnings())
t.Fatalf("Errors: %v", errs)
} }
} }
func TestResourceProvider_Validate_bad(t *testing.T) { func TestResourceProvider_Validate_bad(t *testing.T) {
c := testConfig(t, map[string]interface{}{ c := cty.ObjectVal(map[string]cty.Value{
"invalid": "nope", "invalid": cty.StringVal("nope"),
}) })
warn, errs := Provisioner().Validate(c) resp := New().ValidateProvisionerConfig(provisioners.ValidateProvisionerConfigRequest{
if len(warn) > 0 { Config: c,
t.Fatalf("Warnings: %v", warn) })
} if !resp.Diagnostics.HasErrors() {
if len(errs) == 0 {
t.Fatalf("Should have errors") t.Fatalf("Should have errors")
} }
} }
@ -59,17 +50,13 @@ exit 0
` `
func TestResourceProvider_generateScript(t *testing.T) { func TestResourceProvider_generateScript(t *testing.T) {
conf := map[string]interface{}{ inline := cty.ListVal([]cty.Value{
"inline": []interface{}{ cty.StringVal("cd /tmp"),
"cd /tmp", cty.StringVal("wget http://foobar"),
"wget http://foobar", cty.StringVal("exit 0"),
"exit 0", })
},
}
out, err := generateScripts( out, err := generateScripts(inline)
schema.TestResourceDataRaw(t, Provisioner().(*schema.Provisioner).Schema, conf),
)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -84,34 +71,28 @@ func TestResourceProvider_generateScript(t *testing.T) {
} }
func TestResourceProvider_generateScriptEmptyInline(t *testing.T) { func TestResourceProvider_generateScriptEmptyInline(t *testing.T) {
p := Provisioner().(*schema.Provisioner) inline := cty.ListVal([]cty.Value{cty.StringVal("")})
conf := map[string]interface{}{
"inline": []interface{}{""},
}
_, err := generateScripts(schema.TestResourceDataRaw( _, err := generateScripts(inline)
t, p.Schema, conf))
if err == nil { if err == nil {
t.Fatal("expected error, got none") t.Fatal("expected error, got none")
} }
if !strings.Contains(err.Error(), "Error parsing") { if !strings.Contains(err.Error(), "empty string") {
t.Fatalf("expected parsing error, got: %s", err) t.Fatalf("expected empty string error, got: %s", err)
} }
} }
func TestResourceProvider_CollectScripts_inline(t *testing.T) { func TestResourceProvider_CollectScripts_inline(t *testing.T) {
conf := map[string]interface{}{ conf := map[string]cty.Value{
"inline": []interface{}{ "inline": cty.ListVal([]cty.Value{
"cd /tmp", cty.StringVal("cd /tmp"),
"wget http://foobar", cty.StringVal("wget http://foobar"),
"exit 0", cty.StringVal("exit 0"),
}, }),
} }
scripts, err := collectScripts( scripts, err := collectScripts(cty.ObjectVal(conf))
schema.TestResourceDataRaw(t, Provisioner().(*schema.Provisioner).Schema, conf),
)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -132,13 +113,19 @@ func TestResourceProvider_CollectScripts_inline(t *testing.T) {
} }
func TestResourceProvider_CollectScripts_script(t *testing.T) { func TestResourceProvider_CollectScripts_script(t *testing.T) {
conf := map[string]interface{}{ p := New()
"script": "testdata/script1.sh", schema := p.GetSchema().Provisioner
conf, err := schema.CoerceValue(cty.ObjectVal(map[string]cty.Value{
"scripts": cty.ListVal([]cty.Value{
cty.StringVal("testdata/script1.sh"),
}),
}))
if err != nil {
t.Fatal(err)
} }
scripts, err := collectScripts( scripts, err := collectScripts(conf)
schema.TestResourceDataRaw(t, Provisioner().(*schema.Provisioner).Schema, conf),
)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -159,17 +146,21 @@ func TestResourceProvider_CollectScripts_script(t *testing.T) {
} }
func TestResourceProvider_CollectScripts_scripts(t *testing.T) { func TestResourceProvider_CollectScripts_scripts(t *testing.T) {
conf := map[string]interface{}{ p := New()
"scripts": []interface{}{ schema := p.GetSchema().Provisioner
"testdata/script1.sh",
"testdata/script1.sh", conf, err := schema.CoerceValue(cty.ObjectVal(map[string]cty.Value{
"testdata/script1.sh", "scripts": cty.ListVal([]cty.Value{
}, cty.StringVal("testdata/script1.sh"),
cty.StringVal("testdata/script1.sh"),
cty.StringVal("testdata/script1.sh"),
}),
}))
if err != nil {
log.Fatal(err)
} }
scripts, err := collectScripts( scripts, err := collectScripts(conf)
schema.TestResourceDataRaw(t, Provisioner().(*schema.Provisioner).Schema, conf),
)
if err != nil { if err != nil {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
@ -192,25 +183,28 @@ func TestResourceProvider_CollectScripts_scripts(t *testing.T) {
} }
func TestResourceProvider_CollectScripts_scriptsEmpty(t *testing.T) { func TestResourceProvider_CollectScripts_scriptsEmpty(t *testing.T) {
p := Provisioner().(*schema.Provisioner) p := New()
conf := map[string]interface{}{ schema := p.GetSchema().Provisioner
"scripts": []interface{}{""},
conf, err := schema.CoerceValue(cty.ObjectVal(map[string]cty.Value{
"scripts": cty.ListVal([]cty.Value{cty.StringVal("")}),
}))
if err != nil {
t.Fatal(err)
} }
_, err := collectScripts(schema.TestResourceDataRaw( _, err = collectScripts(conf)
t, p.Schema, conf))
if err == nil { if err == nil {
t.Fatal("expected error") t.Fatal("expected error")
} }
if !strings.Contains(err.Error(), "Error parsing") { if !strings.Contains(err.Error(), "empty string") {
t.Fatalf("Expected parsing error, got: %s", err) t.Fatalf("Expected empty string error, got: %s", err)
} }
} }
func TestProvisionerTimeout(t *testing.T) { func TestProvisionerTimeout(t *testing.T) {
o := new(terraform.MockUIOutput) o := cli.NewMockUi()
c := new(communicator.MockCommunicator) c := new(communicator.MockCommunicator)
disconnected := make(chan struct{}) disconnected := make(chan struct{})
@ -231,13 +225,11 @@ func TestProvisionerTimeout(t *testing.T) {
c.UploadScripts = map[string]string{"hello": "echo hello"} c.UploadScripts = map[string]string{"hello": "echo hello"}
c.RemoteScriptPath = "hello" c.RemoteScriptPath = "hello"
p := Provisioner().(*schema.Provisioner) conf := map[string]cty.Value{
conf := map[string]interface{}{ "inline": cty.ListVal([]cty.Value{cty.StringVal("echo hello")}),
"inline": []interface{}{"echo hello"},
} }
scripts, err := collectScripts(schema.TestResourceDataRaw( scripts, err := collectScripts(cty.ObjectVal(conf))
t, p.Schema, conf))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }