Thursday, April 28, 2022

[SOLVED] Ansible yum module to install a list of packages AND remove any other packages

Issue

I have to deal with new machines (same OS version on all) that have been previously managed manually by many different admins.

The purpose is to use Ansible to make all these machines sharing the same list of installed packages,
AND remove any packages not in the list that might be installed already.

Is this feasible with Ansible ?

vars:
  - yum_rpm:
    - tcpdump
    - tmux
    - psacct

tasks:
  - name: "Install all package in our list"
    yum:
      name: "{{ yum_rpm }}"
      state: absent
      update_cache: no

  - name: "Remove any other unexpected package already installed"
    ## NO IDEA

Solution

Building up on @gary lopez answer to add security and performance.

First you will need to get an actual list of all packages you want to see installed on your final machine, including the default ones that come with the system. I assume that list will be in var yum_rpm

Once you have that, the next step is to get the list of currently installed packages on the machine. To create an actual list we can reuse:

  - name: Get installed packages
    yum:
      list: installed
    register: __yum_packages

  - name: Make installed packages a list of names
    set_fact:
      installed_packages: "{{ __yum_packages.results | map(attribute='name') | list }}"

From there, adding and removing is just a matter of making a difference on lists. The goal here is to avoid looping on the yum module package by package (because it is damn slow and listed as a bad practice on the module documentation page) and to make the install and remove operations in one go.

  - name: align packages on system to expected
    yum:
      name: "{{ item.packages }}"
      state: "{{ item.state }}"
    loop:
      - packages: "{{ yum_rpm | difference(installed_packages) }}"
        state: present
      - packages: "{{ installed_packages | difference(yum_rpm) }}"
        state: absent
    when: item.packages | length > 0



Answered By - Zeitounator
Answer Checked By - Pedro (WPSolving Volunteer)