Running apt-get autoremove with ansible

I maintain a flock of EC2 servers with ansible. The servers are regularly updates and upgraded using the apt module.

When I manually tried to upgrade a server, I received the following message:

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

Is there a way to run sudo apt-get autoremove with ansible?


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


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"