Removing Snap packages from Ubuntu using Ansible

Jul 18, 2022, by Rovshan Mirza

Let's admit it, not everyone likes Snap packages for different reasons. Being a casual Linux user myself, I prefer using only one package manager that works. There is just so much stuff to learn about Linux, and I find it unnecessary to learn snap in addition to apt. Another reason why I don't want Snap is because it is really slow at starting certain apps like Firefox. Maybe I will start using it in the future, but not at the moment.

So, ready to nuke Snap? Here is how it's done using Ansible in easy mode.

Prerequisites

1. Create Ansible Playbook

Create ansible-desktop project folder with below subfolders and files.

ansible-desktop
│ local1.yml
│ ansible.cfg
│ inventory

└───files
│ │ nosnap.pref

└───tasks
│ remove_snap.yml
  • ansible-desktop, files and tasks are folders, the rest are files.

ansible.cfg file:

[defaults]
inventory = inventory

inventory file:

[local]
localhost ansible_connection=local

local1.yml file:

---

- hosts: localhost
connection: local
become: true

tasks:
- include_tasks: tasks/remove_snap.yml
  • hosts and connection values are what we defined in inventory file above.
  • become:true means that Ansible will run as sudo.
  • include_tasks is used to import task files inside tasks folder.

tasks/remove_snap.yml file:

- name: Get list of all packages
package_facts:
manager: auto

- name: Stop and disable Snap
service:
name: snapd.service
state: stopped
enabled: no
when: "'snapd' in ansible_facts.packages"

- name: Remove Snap
apt:
name: snapd
state: absent
purge: yes
autoremove: yes
when: "'snapd' in ansible_facts.packages"

- name: Prevent Snap installs
copy:
src: files/nosnap.pref
dest: /etc/apt/preferences.d/
owner: root
group: root
mode: 0440
when: "'snapd' in ansible_facts.packages"

In tasks/remove_snap.yml task file, we are:

  • collecting information about default package manager, apt, by setting manager to auto.
  • stopping and disabling snapd service if it's present in ansible_facts.packages information collected earlier.
  • purging and removing snapd.
  • preventing snapd from installing in the future. Sometimes when you try to install certain packages using apt, it may reinstall snap if the package is only available in snap. So, we are trying to avoid this from happening using nosnap.pref file below.

files/nosnap.pref file:

Package: snapd
Pin: release a=*
Pin-Priority: -10

2. Run Ansible Playbook

Now, execute below command from Terminal. After it's completed, Snap package manager with all Snap packages should be gone. And, it should prevent apt from installing snapd again.

sudo ansible-playbook local1.yml

Hopefully, this was helpful. I will be adding more tasks soon. Stay tuned!