'Ansible how to install a package only if same version not installed

I am trying to check the existing version of the package and run the install task if the same version is not been installed already.

Below is the code I am trying.

- name: Check for existing mono installation
  command: "mono --version"
  register: current_mono
  ignore_errors: true

- name: Running "make install" for Mono
  command: make install
  args: 
    chdir: "{{ mono_install_dir }}"
  become: yes
  when: "mono_version|string not in current_mono.stdout"

  • First time this will fail because there won't be a stdout in current_mono var.

How to achieve this while running for the first time?



Solution 1:[1]

Since you are using make install you are using shell modules.

  vars:
    software_version: "1.2.3"

  tasks:

First time this will fail ...

This is not absolutely necessary when using the following approach

  - name: Check for existing version
    shell:
      cmd: software --version
      warn: false
    register: result
    changed_when: false
    failed_when: false

Please take note that some software packages like Java or Python are reporting his version to stderr.

  - name: Show result
    debug:
      msg: "{{ result.stderr }}"

Now you can run your installer.

  - name: Install latest version
    shell:
      cmd: "echo 'installing ...'"
      warn: false
    register: result
    when: "software_version | string not in result.stderr"

  - name: Show result
    debug:
      msg: "{{ result.stdout | default('was on latest version') }}"

You could test this sample playbook by using java or python as software.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1