diff --git a/pkg/util/ansible/playbook.go b/pkg/util/ansible/playbook.go index b6de3ddb67..83a57213b1 100644 --- a/pkg/util/ansible/playbook.go +++ b/pkg/util/ansible/playbook.go @@ -55,6 +55,7 @@ type Playbook struct { Inventory Inventory Modules []Module PrivateKey []byte + Files map[string][]byte tmpdir string noCleanOnExit bool @@ -77,6 +78,7 @@ func (pb *Playbook) Copy() *Playbook { pb1.Inventory = gotypes.DeepCopy(pb.Inventory).(Inventory) pb1.Modules = gotypes.DeepCopy(pb.Modules).([]Module) pb1.PrivateKey = gotypes.DeepCopy(pb.PrivateKey).([]byte) + pb1.Files = gotypes.DeepCopy(pb.Files).(map[string][]byte) return pb1 } @@ -160,6 +162,22 @@ func (pb *Playbook) Run(ctx context.Context) (err error) { } } + // write out files + for name, content := range pb.Files { + path := filepath.Join(tmpdir, "files", name) + dir := filepath.Dir(path) + err = os.MkdirAll(dir, os.FileMode(0700)) + if err != nil { + err = errors.WithMessagef(err, "mkdir -p %s", dir) + return + } + err = ioutil.WriteFile(path, content, os.FileMode(0600)) + if err != nil { + err = errors.WithMessagef(err, "writing file %s", name) + return + } + } + // run modules one by one var errs []error defer func() { @@ -185,6 +203,7 @@ func (pb *Playbook) Run(ctx context.Context) (err error) { args = append(args, "--private-key", privateKey) } cmd := exec.CommandContext(ctx, "ansible", args...) + cmd.Dir = pb.tmpdir cmd.Env = os.Environ() cmd.Env = append(cmd.Env, "ANSIBLE_HOST_KEY_CHECKING=False") stdout, _ := cmd.StdoutPipe() diff --git a/pkg/util/ansible/playbook_test.go b/pkg/util/ansible/playbook_test.go index f859dcd219..d0ebcc3616 100644 --- a/pkg/util/ansible/playbook_test.go +++ b/pkg/util/ansible/playbook_test.go @@ -17,6 +17,7 @@ package ansible import ( "context" "os/exec" + "reflect" "testing" ) @@ -45,10 +46,37 @@ func TestPlaybook(t *testing.T) { { Name: "ping", }, + { + Name: "copy", + Args: []string{ + "src=afile", + "dest=/tmp/afile", + }, + }, + { + Name: "copy", + Args: []string{ + "src=adir/afile", + "dest=/tmp/adirfile", + }, + }, } - err := pb.Run(context.TODO()) - if err != nil { - t.Fatalf("not expecting err: %v", err) + pb.Files = map[string][]byte{ + "afile": []byte("afilecontent"), + "adir/afile": []byte("afilecontent under adir"), } - t.Logf("%s", pb.Output()) + + t.Run("copy", func(t *testing.T) { + pb2 := pb.Copy() + if !reflect.DeepEqual(pb2, pb) { + t.Errorf("copy and the original should be equal") + } + }) + t.Run("run", func(t *testing.T) { + err := pb.Run(context.TODO()) + t.Logf("%s", pb.Output()) + if err != nil { + t.Fatalf("not expecting err: %v", err) + } + }) }