3

When a VM is first created, it gets an install user that is used to run the provisioning. I want to remove this user at the last step because it's not necessarily secure and it's unnecessary. However, Packer runs all of the provisioners as this user. I've tried using Ansible, but it still seems to be using this user in some capacity and thus the Ansible playbook cannot actually remove it without failing (saying that there programs still running as the given user). Rather than bumble around, I'm asking if anyone has any ideas as to how to achieve this goal, which should be simple and has turned out not to be.

siride
  • 569
  • 2
  • 8
  • 18

3 Answers3

5

I found another way that works with packer 1.7 for QEMU, VMware, and VirtualBox. You can remove the user in the shutdown command. This method assumes the user has sudo access.

shutdown_command   = "sudo su root -c \"userdel -rf packer; rm /etc/sudoers.d/90-cloud-init-users; /sbin/shutdown -hP now\""
nibty
  • 151
  • 1
  • 1
  • I can confirm this still works (packer 1.8.6, VirtualBox). And I would add: don't be scared by `userdel`'s message "user foo is currently used by process XYZ"... this is just a warning, but the user gets deleted. – aalazz Mar 30 '23 at 22:59
5

I realize this is a rather old question, but I didn't like the idea of using a cronjob (or cloud-init, or anything that happens after the image would be instantiated) for this, and found what I find to be a better solution using packer itself. This works in Packer 1.4:

{
    "type": "shell",
    "skip_clean": true,
    "execute_command": "chmod +x {{ .Path }}; sudo env {{ .Vars }} {{ .Path }} ; rm -f {{ .Path }}",
    "inline": [
        "rm -f /etc/sudoers.d/90-cloud-init-users",
        "/usr/sbin/userdel -r -f fedora",
    ]
}

This assumes your install user is named fedora — it leverages Packer's skip_clean option to skip the deletion of the shell script after the inline section completes (which, given that the fedora user no longer exists, was guaranteed to fail).

Also note that if you have SSH agent forwarding turned on with packer, this may leave traces of the agent socket behind in the image.

Joey Coleman
  • 151
  • 1
  • 5
  • I tried this on Ubuntu 18.04, however Packer failed in the end of the provisioning because it tried to chdir to the home directory of the deleted user. I would recommend people to go with the /etc/rc.local solution instead. – Bungicasse Feb 25 '20 at 08:30
2

Schedule a cron job to remove the user with @reboot option or add a few lines to rc scripts to do the same.

techraf
  • 4,243
  • 8
  • 29
  • 44
  • I wasn't able to get `@reboot` to work, but having it run once a minute and then delete itself once it runs works well enough. A little irritating, but it works. – siride Apr 05 '17 at 14:36