Ansible apt "Could not get lock /var/lib/dpkg/lock" in CI
The apt module could not acquire the dpkg lock because another process (an unattended-upgrades run, or a parallel task) already holds it. apt is single-writer, so the task fails until the lock is free.
What this error means
An apt task fails with "Failed to lock apt for exclusive operation" or "Could not get lock /var/lib/dpkg/lock-frontend ... It is held by process N (unattended-upgr)".
fatal: [host1]: FAILED! => {"msg": "Failed to lock apt for exclusive operation:
E:Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234
(unattended-upgr)"}Common causes
unattended-upgrades is running on boot
Freshly booted cloud images run background package updates, holding the dpkg lock when your play starts.
A parallel apt task on the same host
Two tasks or plays touch apt at once, and the second cannot acquire the exclusive lock.
How to fix it
Wait for the lock to release
Retry the apt task until the background updater finishes, instead of failing on the first attempt.
- name: Install package
ansible.builtin.apt:
name: nginx
state: present
register: apt_result
until: apt_result is succeeded
retries: 10
delay: 15Disable unattended-upgrades for the run
On hosts you control, stop the background updater before package tasks so the lock is free.
- name: Stop unattended upgrades
ansible.builtin.systemd:
name: unattended-upgrades
state: stopped
become: trueHow to prevent it
- Retry apt tasks with
until/retriesto ride out boot-time updates. - Stop or wait for unattended-upgrades before package tasks.
- Avoid running two apt tasks against one host in parallel.