pkg: ansible: 添加文件内容支持

This commit is contained in:
Yousong Zhou
2019-06-14 10:39:25 +00:00
parent 68ed59eda0
commit 5ec150e7a9
2 changed files with 51 additions and 4 deletions

View File

@@ -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()

View File

@@ -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)
}
})
}