Ansible yum Module Tutorial + Examples


Percy Grunwald's Profile Picture

Written by Percy Grunwald

— Last Updated February 7, 2024

Ansible Course: Productive with Ansible (2024)
Ansible Course: Productive with Ansible (2024)
Go from Ansible beginner to Ansible pro with this full video course.

What does the Ansible yum module do?

Ansible’s yum module is used to manage packages with the yum package manager, which is the default on Red Hat based Linux distributions such as Red Hat Enterprise Linux and CentOS. Most systems require root/superuser permissions to manage packages, which means that become: true is required.

I recommend always using the update_cache: true parameter when installing or updating packages, which forces yum to check if the package cache is out of date and it update it if needed.

- name: ensure wget is installed
  yum:
    name: wget
    state: present
    update_cache: true
  become: true

If you need to manage yum repositories, use the yum_repository module.

If you need to manage packages on Debian-based distributions like Debian or Ubuntu, use the apt module instead.

Ansible yum Module Video Tutorial

If you prefer watching to reading, here’s a full video tutorial from the TopTechSkills YouTube channel covering a many of the points and examples from this article. Feel free to comment on this article or the video if you have any questions.

▶️ Watch on YouTube

When to use the yum module vs apt module

The yum module manages packages using the yum package manager, which is only available on Red Hat Enterprise Linux and CentOS. Debian based Linux distributions such as Debian and Ubuntu use the apt package manager, so you should use the apt module for those distros.

When to use the yum module vs package module

The package module manages packages using whichever package manager is present on the remote host, such as yum, apt or dnf. This appears to be the most convenient way to manage packages, but I advise you to avoid using the package module in any situation.

The biggest reason to avoid it is because the same package may have different names on different distros.

For example: the server package for the popular in-memory database Redis is called redis-server on Debian based distros and redis on Red Hat based distros.

Unless you (and everyone on your team) is intimately familiar with the naming differences for packages across all distributions, using package drastically increases the chance of an error due to package naming. I highly recommend you manage packages using the module specific to the remote host.

The most common pattern for creating roles that can be run across all distributions is to run tasks conditionally based on the ansible_os_family variable:

- name: install redis on RHEL based distros
  yum:
    name: redis
    state: present
    update_cache: true
  become: true
  when: ansible_os_family == 'RedHat'

- name: install redis on Debian based distros 
  apt:
    name: redis-server
    state: present
    update_cache: true
  become: true
  when: ansible_os_family == 'Debian'

Examples

How to install a package with the yum module

Set the name parameter to the package you wish to install and state: present to install a package. If the package is already installed on the remote host (with any version), Ansible will do nothing. If you need a specific version of a package, or to ensure the latest version of a package is installed, please see the following sections.

- name: ensure wget is installed
  yum:
    name: wget
    state: present
    update_cache: true
  become: true

How to install a specific version of a package with the yum module

Add the version and release information to the name parameter to install a specific version of a package, assuming the specific version is available on the system. You can see which versions are available by using the list parameter of the yum module (see following sections) or by running yum --showduplicates list $PACKAGE on the host.

The format of the version string is {{ package_name }}-{{ package_version }}-{{ package_release }}.

- name: ensure a specific version of wget is installed
  yum:
    name: wget-1.14-18.el7
    state: present
    update_cache: true
  become: true

How to install multiple packages with the yum module

The best way to install multiple packages is by passing the list to the name parameter. This method is preferred over using loop because loop will install each package individually, which is very inefficient compared to passing all packages in name.

- name: ensure wget and ruby are installed
  yum:
    name: 
      - wget
      - ruby
    state: present
    update_cache: true
  become: true

How to remove a package with the yum module

Set state: absent to remove a package. I suggest also setting autoremove: true to remove any dependencies that were installed originally, but are no longer required.

- name: ensure wget is not installed
  yum:
    name: wget
    state: absent
    autoremove: true
  become: true

How to update a package with the yum module

Setting state: latest will install the latest version of a package, or update a package that is already installed where a newer version is available. You should

- name: ensure latest version of wget is installed
  yum:
    name: wget
    state: latest
    update_cache: true
  become: true

How to update multiple packages with the yum module

Set the name parameter to a list of package names and state: latest to ensure the latest versions of multiple packages are installed.

- name: ensure latest versions of wget and ruby are installed
  yum:
    name:
      - wget
      - ruby
    state: latest
    update_cache: true
  become: true

How to downgrade a package with the yum module

Set the name to an older package version and allow_downgrade: true to downgrade a package. In the example below, ruby and ruby-libs were both version 2.0.0.648-34.el7_6 before downgrading.

- name: downgrade ruby and ruby-libs to a specific version
  yum:
    name: 
      - ruby-2.0.0.648-33.el7_4
      - ruby-libs-2.0.0.648-33.el7_4
    state: present
    allow_downgrade: true
    update_cache: true
  become: true

How to list available packages with the yum module

Set the list parameter to the name of a package to return a list of available (and installed) packages. Use register to capture the output and use it in other tasks.

- name: list installed and available versions of ruby
  yum:
    list: ruby
  become: true
  when: ansible_os_family == 'RedHat'
  register: yum_output

- name: print available ruby versions
  debug:
    msg: "{{ item.version }}-{{ item.release }}"
  loop: "{{ yum_output.results | selectattr('yumstate', 'equalto', 'available') | list }}"

- debug: var=yum_output

The first debug task will print the following:

ok: [123.123.123.123] => (item={...}) => {
    "msg": "2.0.0.648-33.el7_4"
}
ok: [123.123.123.123] => (item={...}) => {
    "msg": "2.0.0.648-34.el7_6"
}

The last debug task will print the full contents of yum_output:

ok: [123.123.123.123] => {
    "yum_output": {
        "changed": false,
        "failed": false,
        "results": [
            {
                "arch": "x86_64",
                "envra": "0:ruby-2.0.0.648-33.el7_4.x86_64",
                "epoch": "0",
                "name": "ruby",
                "release": "33.el7_4",
                "repo": "base",
                "version": "2.0.0.648",
                "yumstate": "available"
            },
            {
                "arch": "x86_64",
                "envra": "0:ruby-2.0.0.648-34.el7_6.x86_64",
                "epoch": "0",
                "name": "ruby",
                "release": "34.el7_6",
                "repo": "installed",
                "version": "2.0.0.648",
                "yumstate": "installed"
            },
            {
                "arch": "x86_64",
                "envra": "0:ruby-2.0.0.648-34.el7_6.x86_64",
                "epoch": "0",
                "name": "ruby",
                "release": "34.el7_6",
                "repo": "updates",
                "version": "2.0.0.648",
                "yumstate": "available"
            }
        ]
    }
}

How to install package groups with the yum module

yum package and environment groups are collections of packages that are commonly installed together. These are the package groups available on CentOS 7.5, as printed by the yum group list ids command:

Available Environment Groups:
   Minimal Install (minimal)
   Compute Node (compute-node-environment)
   Infrastructure Server (infrastructure-server-environment)
   File and Print Server (file-print-server-environment)
   Cinnamon Desktop (cinnamon-desktop-environment)
   MATE Desktop (mate-desktop-environment)
   Basic Web Server (web-server-environment)
   Virtualization Host (virtualization-host-environment)
   Server with GUI (graphical-server-environment)
   GNOME Desktop (gnome-desktop-environment)
   KDE Plasma Workspaces (kde-desktop-environment)
   Development and Creative Workstation (developer-workstation-environment)
Available Groups:
   Cinnamon (cinnamon-desktop)
   Compatibility Libraries (compat-libraries)
   Console Internet Tools (console-internet)
   Development Tools (development)
   Educational Software (education)
   Electronic Lab (electronic-lab)
   Fedora Packager (fedora-packager)
   General Purpose Desktop (general-desktop)
   Graphical Administration Tools (graphical-admin-tools)
   Haskell (haskell)
   Legacy UNIX Compatibility (legacy-unix)
   MATE (mate-desktop)
   Milkymist (milkymist)
   Scientific Support (scientific)
   Security Tools (security-tools)
   Smart Card Support (smart-card)
   System Administration Tools (system-admin-tools)
   System Management (system-management)
   TurboGears application framework (turbogears)
   Xfce (xfce-desktop)
Done

You can see the packages in the group with yum group info $PACKAGE, e.g. yum group info development:

Group: Development Tools
 Group-Id: development
 Description: A basic development environment.
 Mandatory Packages:
   +autoconf
   +automake
    binutils
   +bison
   +flex
   +gcc
   +gcc-c++
    gettext
   +libtool
    make
   +patch
    pkgconfig
   +redhat-rpm-config
   +rpm-build
   +rpm-sign
 Default Packages:
   +byacc
   +cscope
   +ctags
   +diffstat
   +doxygen
   +elfutils
   +gcc-gfortran
   +git
   +indent
   +intltool
   +patchutils
   +rcs
   +subversion
   +swig
   +systemtap
 Optional Packages:
   ElectricFence
   ant
   babel
   ...

Each type of group has a special way of specifying the name:

  • Environment groups - name: "@^gnome-desktop-environment"
  • Package groups - name: "@development"
- name: ensure development tools are installed
  yum:
    name: "@development"
    state: present
  become: true

How to capture yum module output

Use the register keyword to capture the output of the yum module.

- name: ensure wget is installed
  yum:
    name: wget
    state: present
  become: true
  register: yum_output

- debug: var=yum_output

The debug task above will output the following:

ok: [123.123.123.123] => {
    "yum_output": {
        "changed": true,
        "failed": false,
        "msg": "",
        "rc": 0,
        "results": [
            "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirror.intergrid.com.au\n * epel: epel.mirror.digitalpacific.com.au\n * extras: mirror.intergrid.com.au\n * updates: mirror.optus.net\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.14-18.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version              Repository       Size\n================================================================================\nInstalling:\n wget            x86_64            1.14-18.el7            base            547 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 547 k\nInstalled size: 2.0 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : wget-1.14-18.el7.x86_64                                      1/1 \n  Verifying  : wget-1.14-18.el7.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.14-18.el7                                                     \n\nComplete!\n"
        ]
    }
}

Further reading

Comment & Share