How to use Ansible to autoremove unwanted package dependency with apt

I am trying to use ansible apt autoremove option but it is not working. I wanted to remove all unused Linux kernel and unwanted package dependency with the apt command/apt-get command. How can I run sudo apt-get autoremove on remote Ubuntu/Debian Linux servers with ansible?

To manages apt packages for Debian/Ubuntu and friends use apt module of Ansible. The autoremove is used to remove packages that were automatically installed to satisfy dependencies for other packages and are now no longer needed as dependencies changed or the package(s) needing them were removed in the meantime.

To do so you run the apt command or apt-get command as follows:
$ sudo apt autoremove
$ sudo apt-get autoremove
For removing unused Linux kernel on a Debian/Ubuntu Linux use:
$ sudo apt -y --purge autoremove
## OR ##
$ sudo apt-get -y --purge autoremove

Running sudo apt-get autoremove with ansible

Update your yml file as follows:

          - name: Clean unwanted olderstuff
                    autoremove: yes
                    purge: yes


  1. autoremove : If yes, remove unused dependency packages for all module states except build-dep. It can also be used as the only option. You must use Ansible version 2.1.
  2. purge : This will force purging of configuration files if the module state is set to yes.

Here is my vpn.yml file:

- hosts: vpn
  become: true
  become_user: root
          - name: Updating host using apt
                    update_cache: yes
                    upgrade: dist
          - name: Update kernel to spefic version
                    name: "{{ k_ver }}"
                    state: latest
          - name: Clean unwanted olderstuff
                    autoremove: yes
                    purge: yes

My hosts file:



Run it as follows:
$ ansible-playbook -i hosts vpn.yml
$ export ANSIBLE_HOSTS=~/opshelper/hosts
$ ansible-playbook vpn.yml

A note about running apt autoremove on LXD based vm

You can update your yml file as follows to run same command on three vm named db, proxy, and www as follows:

          - name: Run lxc apt-autoremove on cbz01 lxd host per vm
            command: /usr/bin/lxc exec {{ item }} -- /usr/bin/apt-get --purge -y autoremove
                    - db
                    - proxy
                    - www

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.