Packer can't execute shell provisioner as sudo

Georg Heiler picture Georg Heiler · Jan 31, 2018 · Viewed 11.5k times · Source

I have a shell provisioner in packer connected to a box with user vagrant

{
  "environment_vars": [
    "HOME_DIR=/home/vagrant"
  ],
  "expect_disconnect": true,
  "scripts": [
    "scripts/foo.sh"
  ],
  "type": "shell"
}

where the content of the script is:

whoami
sudo su
whoami

and the output strangely remains:

==> virtualbox-ovf: Provisioning with shell script: scripts/configureProxies.sh
    virtualbox-ovf: vagrant
    virtualbox-ovf: vagrant

why cant I switch to the root user? How can I execute statements as root? Note, I do not want to quote all statements like sudo "statement |foo" but rather globally switch user like demonstrated with sudo su

Answer

Rickard von Essen picture Rickard von Essen · Jan 31, 2018

You should override the execute_command. Example:

  "provisioners": [
    {
      "execute_command": "echo 'vagrant' | {{.Vars}} sudo -S -E sh -eux '{{.Path}}'",
      "scripts": [
        "scripts/foo.sh"
      ],
      "type": "shell"
    }
  ],