Skip to content
Latchkey

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)".

ansible
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.

site.yml
- name: Install package
  ansible.builtin.apt:
    name: nginx
    state: present
  register: apt_result
  until: apt_result is succeeded
  retries: 10
  delay: 15

Disable unattended-upgrades for the run

On hosts you control, stop the background updater before package tasks so the lock is free.

site.yml
- name: Stop unattended upgrades
  ansible.builtin.systemd:
    name: unattended-upgrades
    state: stopped
  become: true

How to prevent it

  • Retry apt tasks with until/retries to ride out boot-time updates.
  • Stop or wait for unattended-upgrades before package tasks.
  • Avoid running two apt tasks against one host in parallel.

Frequently asked questions

What causes ""Could not get lock /var/lib/dpkg/lock""?
Freshly booted cloud images run background package updates, holding the dpkg lock when your play starts.
How do I fix "Could not get lock /var/lib/dpkg/lock"?
Retry the apt task until the background updater finishes, instead of failing on the first attempt.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card