0

I want to create an AWS AMI using packer. Part of the setup process is running a build script, that will setup services and configure the environment for a system user averagejoe that is not root. The setup script basically looks like this:

# some cmds that need to be run by averagejoe
echo "alias ll='ls -Alfh'" > $HOME/.bashrc
# some cmds that need to be run by a privileged user
sudo firewall-cmd --zone=public --permanent --add-port=3389/tcp

Thus, part of the script should be executed as the system user averagejoe, part of the script should be executed as privileged user using sudo. Therefore, running the whole script as privileged user as suggested here is not an option.

How can I provide the sudo pwd when the script gets executed by the packer provisioner? I thought of a 3-stage approach, first reconfiguring sudo to not require a password, then run the setup script and then reset sudo to requesting passwords, but is there anything more elegant?

2 Answers 2

0

I ended up switching off sudo passwords for the time when the setup script gets executed, like so:

    "provisioners": [
    {
        "type": "shell",
        "script": "project/packer/pwd_less_sudo.sh",
        "execute_command": "echo {{user `password`}} | sudo -S bash -c '{{ .Path }}'"
    },
    {
        "type": "shell",
        "script": "project/scripts/bootstrap.sh",
        "execute_command": "{{ .Path }}  --branch feature/ods-devenv"
    },
    {
        "type": "shell",
        "script": "project/packer/pwd_sudo.sh",
        "execute_command": "echo {{user `password`}} | sudo -S bash -c '{{ .Path }}'"
    }
]

where pwd_less_sudo.sh is

#!/usr/bin/env bash
# make wheel pwd free
sudo sed -i '0,/%wheel[[:space:]]*ALL=(ALL)[[:space:]]*ALL/{s||%wheel        ALL=(ALL)       NOPASSWD: ALL|}' /etc/sudoers

and pwd_sudo.sh is

#!/usr/bin/env bash
# give wheel their pwd back
sudo sed -i '0,/%wheel[[:space:]]*ALL=(ALL)[[:space:]]*NOPASSWD:[[:space:]]*ALL/{s||%wheel  ALL=(ALL)       ALL|}' /etc/sudoers
0

Some operating systems default to a non-root user. For example if you login as ubuntu and can sudo using the password packer, then you'll want to change execute_command to be:

"provisioners": [
  {
    "type": "shell",
    "exec_command": "echo 'your-password' | sudo -S [your-comand-here]"
  }       
]

The -S flag tells sudo to read the password from stdin, which in this case is being piped in with the value of packer.

This error happend to me because this section of packer:

"shutdown_command": "echo 'password-here' | sudo -S shutdown -P now",

Where i put incorrect password

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .