Merge pull request #1698 from jmassara/chef_client_prevent_sudo

Use sudo only if prevent_sudo is not set
This commit is contained in:
Seth Vargo 2014-11-27 11:05:31 -05:00
commit e5c0bf14df
2 changed files with 68 additions and 2 deletions

View File

@ -338,8 +338,14 @@ func (p *Provisioner) createJson(ui packer.Ui, comm packer.Communicator) (string
func (p *Provisioner) createDir(ui packer.Ui, comm packer.Communicator, dir string) error {
ui.Message(fmt.Sprintf("Creating directory: %s", dir))
mkdirCmd := fmt.Sprintf("mkdir -p '%s'", dir)
if !p.config.PreventSudo {
mkdirCmd = "sudo " + mkdirCmd
}
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("sudo mkdir -p '%s'", dir),
Command: mkdirCmd,
}
if err := cmd.StartWithUi(comm, ui); err != nil {
@ -387,8 +393,14 @@ func (p *Provisioner) cleanClient(ui packer.Ui, comm packer.Communicator, node s
func (p *Provisioner) removeDir(ui packer.Ui, comm packer.Communicator, dir string) error {
ui.Message(fmt.Sprintf("Removing directory: %s", dir))
rmCmd := fmt.Sprintf("rm -rf '%s'", dir)
if !p.config.PreventSudo {
rmCmd = "sudo " + rmCmd
}
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("sudo rm -rf %s", dir),
Command: rmCmd,
}
if err := cmd.StartWithUi(comm, ui); err != nil {

View File

@ -1,8 +1,10 @@
package chefclient
import (
"bytes"
"io/ioutil"
"os"
"strings"
"testing"
"github.com/mitchellh/packer/packer"
@ -135,3 +137,55 @@ func TestProvisionerPrepare_serverUrl(t *testing.T) {
t.Fatalf("err: %s", err)
}
}
func TestProvisioner_createDir(t *testing.T) {
p1 := &Provisioner{config: Config{PreventSudo: true}}
p2 := &Provisioner{config: Config{PreventSudo: false}}
comm := &packer.MockCommunicator{}
ui := &packer.BasicUi{
Reader: new(bytes.Buffer),
Writer: new(bytes.Buffer),
}
if err := p1.createDir(ui, comm, "/tmp/foo"); err != nil {
t.Fatalf("err: %s", err)
}
if strings.HasPrefix(comm.StartCmd.Command, "sudo") {
t.Fatalf("createDir should not use sudo, got: \"%s\"", comm.StartCmd.Command)
}
if err := p2.createDir(ui, comm, "/tmp/foo"); err != nil {
t.Fatalf("err: %s", err)
}
if !strings.HasPrefix(comm.StartCmd.Command, "sudo") {
t.Fatalf("createDir should use sudo, got: \"%s\"", comm.StartCmd.Command)
}
}
func TestProvisioner_removeDir(t *testing.T) {
p1 := &Provisioner{config: Config{PreventSudo: true}}
p2 := &Provisioner{config: Config{PreventSudo: false}}
comm := &packer.MockCommunicator{}
ui := &packer.BasicUi{
Reader: new(bytes.Buffer),
Writer: new(bytes.Buffer),
}
if err := p1.removeDir(ui, comm, "/tmp/foo"); err != nil {
t.Fatalf("err: %s", err)
}
if strings.HasPrefix(comm.StartCmd.Command, "sudo") {
t.Fatalf("removeDir should not use sudo, got: \"%s\"", comm.StartCmd.Command)
}
if err := p2.removeDir(ui, comm, "/tmp/foo"); err != nil {
t.Fatalf("err: %s", err)
}
if !strings.HasPrefix(comm.StartCmd.Command, "sudo") {
t.Fatalf("removeDir should use sudo, got: \"%s\"", comm.StartCmd.Command)
}
}