Running apt-get autoremove with ansible
Solution 1:
Support for the apt-get
option --auto-remove
is now built into Ansible's apt
(option autoremove
) as of version 2.1 Official documentation is at http://docs.ansible.com/ansible/apt_module.html
- name: Remove dependencies that are no longer required
apt:
autoremove: yes
The merge happened here.
Note that autoclean
is also available as of 2.4
Solution 2:
This simplified method requires one task only
- name: Autoremove unused packages
command: apt-get -y autoremove
register: autoremove_output
changed_when: "'The following packages will be REMOVED' in autoremove_output.stdout"
Solution 3:
You can do it with command
(untested):
- 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"
However, I think it could be risky to run autoremove
automatically. Because of system administration errors that you've made in the past (these could be in your ansible code), it's possible that a package that is needed can at some point be falsely detected as autoremovable, and this could stop the server from working. On the other hand, it's no big deal to leave unused packages on the system, and it's not very common unless you make a major change in the server's setup.
Therefore, I would stay away from autoremoving packages without confirmation from a human.
Solution 4:
This is a variation on the solution Antonis Christofides provided. It is tested and works for me. I avoided using ignore_errors in the check command. Otherwise it generally takes the same approach.
- 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"
Solution 5:
A variation that highlights the change in packages (first task will be appropriately colored green or yellow):
- name: check if packages need to be autoremoved
shell: apt-get --dry-run autoremove | grep "to remove" | sed "s/^[0-9]\+ upgraded, [0-9]\+ newly installed, \([0-9]\+\) to remove and [0-9]\+ not upgraded\.$/\1/"
register: check_autoremove
changed_when: check_autoremove.stdout != "0"
- name: autoremove unused packages
command: apt-get -y autoremove
when: check_autoremove.changed