使用 ansible 运行 apt-get autoremove

Ada*_*tan 25 apt ansible

我用 ansible 维护了一群 EC2 服务器。服务器使用apt 模块定期更新和升级。

当我手动尝试升级服务器时,收到以下消息:

$ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages were automatically installed and are no longer required:
  linux-headers-3.13.0-29 linux-headers-3.13.0-29-generic
  linux-headers-3.13.0-32 linux-headers-3.13.0-32-generic
  linux-image-3.13.0-29-generic linux-image-3.13.0-32-generic
Use 'apt-get autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Run Code Online (Sandbox Code Playgroud)

有没有办法sudo apt-get autoremove用ansible运行?

oal*_*ers 29

从版本 2.1 开始,对该apt-get选项的支持--auto-remove现已内置到 Ansible 的apt(选项autoremove)中。官方文档位于http://docs.ansible.com/ansible/apt_module.html

- name: Remove dependencies that are no longer required
  apt:
    autoremove: yes
Run Code Online (Sandbox Code Playgroud)

合并发生在这里

请注意,autoclean从 2.4 开始也可用


cor*_*opy 14

这种简化的方法只需要一项任务

  - name: Autoremove unused packages
    command: apt-get -y autoremove
    register: autoremove_output
    changed_when: "'The following packages will be REMOVED' in autoremove_output.stdout"
Run Code Online (Sandbox Code Playgroud)


Ant*_*des 9

您可以使用command(未经测试):

  - name: Check if anything needs autoremoving
    shell: apt-get -y --dry-run autoremove | grep -q "0 to remove"
    register: check_autoremove
    ignore_errors: True
    changed_when: False
    always_run: True

  - name: Autoremove unused packages
    command: apt-get -y autoremove
    when: "check_autoremove.rc != 0"
Run Code Online (Sandbox Code Playgroud)

但是,我认为autoremove自动运行可能会有风险。由于您过去犯过的系统管理错误(这些可能在您的 ansible 代码中),需要的包可能在某个时候被错误地检测为可自动删除,这可能会阻止服务器工作。另一方面,将未使用的包留在系统上没什么大不了的,除非您对服务器的设置进行重大更改,否则这种情况并不常见。

因此,我不会在没有人确认的情况下自动删除包。


Mar*_*agh 6

这是 Antonis Christofides 提供的解决方案的变体。它已经过测试并且对我有用。我避免在 check 命令中使用 ignore_errors 。否则,它通常采用相同的方法。

- name: Check if packages need to be autoremoved
  command: apt-get --dry-run autoremove
  register: check_autoremove
  changed_when: False
- name: Autoremove unused packages
  command: apt-get -y autoremove
  when: "'packages will be REMOVED' in check_autoremove.stdout"
Run Code Online (Sandbox Code Playgroud)