Ansible playbook 无法锁定 apt

Ansible playbook fails to lock apt

我接手了一个 运行 在 Ansible 上进行服务器配置和管理的项目。我是 Ansible 的新手,但多亏了很好的文档,我才开始了解它。 我仍然遇到错误,输出如下:

failed: [build] (item=[u'software-properties-common', u'python-pycurl', u'openssh-server', u'ufw', u'unattended-upgrades', u'vim', u'curl', u'git', u'ntp']) => {"failed": true, "item": ["software-properties-common", "python-pycurl", "openssh-server", "ufw", "unattended-upgrades", "vim", "curl", "git", "ntp"], "msg": "Failed to lock apt for exclusive operation"}

剧本是 运行 和 sudo: yes,所以我不明白为什么我会收到此错误(看起来像权限错误)。知道如何追踪吗?

- name: "Install very important packages"
  apt: pkg={{ item }} update_cache=yes state=present
  with_items:
    - software-properties-common # for apt repository management
    - python-pycurl # for apt repository management (Ansible support)
    - openssh-server
    - ufw
    - unattended-upgrades
    - vim
    - curl
    - git
    - ntp

剧本:

- hosts: build.url.com
  sudo: yes
  roles:
    - { role: postgresql, tags: postgresql }
    - { role: ruby, tags: ruby }
    - { role: build, tags: build }

在配置 Ubuntu(可能还有一些其他发行版)时,这是一种非常常见的情况。您尝试 运行 Ansible,而自动更新在后台 运行ning(这是设置新机器后立即发生的情况)。由于 APT 使用信号量,Ansible 被踢出。

剧本没问题,最简单的验证方法是稍后运行它(自动更新过程完成后)。

对于永久解决方案,您可能需要:

  • 使用禁用自动更新的OS图像
  • 在 Ansible 剧本中添加一个显式循环以重复失败的任务直到成功

我刚刚在新虚拟机上遇到了同样的问题。我尝试了很多方法,包括重试 apt 命令,但最后唯一的方法是删除无人值守的升级。

我在这里使用 raw 命令,因为此时 VM 没有安装 Python,所以我需要先安装它,但我需要一个 可靠 apt

因为它是一个虚拟机,我通过将它重置为快照来测试剧本,系统日期已关闭,这迫使我使用 date -s 命令以避免 SSL 出现问题apt 命令期间的证书。此 date -s 触发了无人值守升级。

所以剧本的这个片段基本上是与在新系统中禁用无人值守升级相关的部分。它们是我在新系统上发出的第一条命令。

- name: Disable timers for unattended upgrade, so that none will be triggered by the `date -s` call.
  raw: systemctl disable --now {{item}}
  with_items:
    - 'apt-daily.timer'
    - 'apt-daily-upgrade.timer'

- name: Reload systemctl daemon to apply the new changes
  raw: systemctl daemon-reload

# Syncing time is only relevant for testing, because of the VM's outdated date.
#- name: Sync time
#  raw: date -s "{{ lookup('pipe', 'date') }}"

- name: Wait for any possibly running unattended upgrade to finish
  raw: systemd-run --property="After=apt-daily.service apt-daily-upgrade.service" --wait /bin/true

- name: Purge unattended upgrades
  raw: apt-get -y purge unattended-upgrades    

- name: Update apt cache
  raw: apt-get -y update

- name: If needed, install Python
  raw: test -e /usr/bin/python || apt-get -y install python

由于无人值守升级导致的锁定问题,其他任何事情都会导致 apt 命令随机失败。