Ssh – Packer with ansible from local works but from another server ask for root permissions

ansibleJenkinspackersshsudo

For a bit of context, I'm using packer with an ansible provisioner to create AMI images on AWS.

The relevant parts of the packer and ansible:

packer.json

"provisioners": [{
  "type": "shell",
  "inline": [
    "sleep 15",
    "sudo apt-get update",
    "sudo apt-get install -y aptitude python"
  ]
}, {
  "type": "ansible",
  "playbook_file": "../provision/ansible-playbook.yml",
  "groups": ["webworker"],
  "extra_arguments": [
    "--become-method=sudo"
  ]
}]

tasks.yml

- name: Install tools
  become: true
  apt:
    name: "{{ item }}"
    state: latest
  with_items:
    - build-essential
    - git

On my local machine, everything goes ok.

But as part of a CI this is, using our Jenkins server to run this packer script but it fails on the first ansible task that have a become in place, in this case the first step is installing some tools via apt module:

amazon-ebs:         "W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)",
amazon-ebs:         "E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)",
amazon-ebs:         "E: Unable to lock directory /var/lib/apt/lists/",
amazon-ebs:         "W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)",
amazon-ebs:         "W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)",
amazon-ebs:         "E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)",
amazon-ebs:         "E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?"

I've checked the permissions, the user, and even if there was another apt running in the background that had the lock: nothing.

The more interesting thing is that if I replace the ansible with a command with sudo aptitude ... it works, and also that previous to the ansible task there's a shell provisioner that also runs apt-get without errors.

Again, this work from my machine (and from two other computers), just not from a server. I don't have an ansible.cfg in any machine (not even the default one).

Best Answer

I ran into this problem using packer to create an AWS AMI for Ubuntu 16.04. Are you using Ubuntu?

Ubuntu 16.04 defaults to running uattended-upgrades automatically (out of the box). What happens is that the first time a box is brought up, unattended-upgrades locks apt (see /var/lib/dpkg/lock), and then provisioning scripts error out if they install anything via apt.

See here to more details https://github.com/ansible/ansible/issues/4355#issuecomment-286184925

Also here:- https://github.com/geerlingguy/packer-ubuntu-1604/issues/3