Sir_Yaro
Sir_Yaro

Reputation: 35

How to get latest package version with Ansible

I'm trying to replicate the command yum check-update package_name preferably with the Ansible yum module.

It provides an information to what version package would be updated after yum update execution (or ansible equivalent). For example:

root@host: $ yum check-update kernel
[...]
kernel.x86_64                                                    3.10.0-1160.80.1.el7
[...]
root@host: $

I tried various combination of

- name: Xyz
  ansible.builtin.yum:
    list: updates
    update_cache: true

But I can't limit it to a single package or pattern (like java*).

What I ended up with is ugly and slow (because of the download) workaround:

- name: Check latest available xyz version
  yum:
    name: xyz
    state: latest
    download_only: true
  become: true
  register: _result

- name: Register xyz version
  set_fact:
    latestXyz: "{{ _result.changes.updated[0][1] | regex_search('xyz-(.+).x86_64.*', '\\1') }}"

Is there any better way to achieve this?

Upvotes: 3

Views: 2420

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39109

One pretty easy way to achieve this is to run the yum module as you would to update the package, but enforce a dry run on it, with the check_mode option, and register the result of this task.

Inspecting the result, you'll realise that the module will list you the current version of the package and the version it would have been updated to, would it not have been run in dry run.

Given, for example

- yum:
    name: expat
    state: latest
  check_mode: true
  register: yum_latest_versions

Will populate the variable yum_latest_versions on a fedora:35 container with:

yum_latest_versions:
  ansible_facts:
    pkg_mgr: dnf
  changed: true
  failed: false
  msg: 'Check mode: No changes made, but would have if not in check mode'
  rc: 0
  results:
  - 'Installed: expat-2.5.0-1.fc35.x86_64'
  - 'Removed: expat-2.4.9-1.fc35.x86_64'

Then to extract, you can indeed use a regex to search in the result:

- debug:
    msg: >-
      {{
        (
          yum_latest_versions.results
            | map('regex_search', '^Installed: expat\-(.*)\.x86_64$', '\1')
        ).0.0
      }}

Finally yields:

msg: 2.5.0-1.fc37

Upvotes: 2

Related Questions