1

I need to create one single play in a playbook where the playbook is failed when a condition is met.

To be more specific, if the user attempts to reinstall a version of openjdk which is already installed on the target server, the play will make this check and fail, the rest of the plays in the task list being cancelled onwards.

So far I have attempted the following play:

- name: Checking the old version
  shell: java -version 2> openjdk_version.txt ; grep -i "openjdk version" openjdk_version.txt > java_version_used.txt ; cut -d " " -f 3 java_version_used.txt | tr -d '"'
  register: jdk_old_vers

- name: Comparing the new version with the older version
  fail:
    msg: The version selected for installation already exists on the server. Make sure you are selecting a different version! The play will now be stopped.
  when: "{{ jdk_new_version }} == {{ jdk_old_vers.stdout }}"

The play results in error:

"msg": "The conditional check '{{ jdk_new_version }} != {{ jdk_old_vers.stdout }}' failed. The error was: Invalid conditional detected: invalid syntax

Tried with:

when: "{{ jdk_new_version }} = {{ jdk_old_vers.stdout }}"

but still fails with the same error.

Value of jdk_new_version=1.8.0_332.

Can't seem to understand where's my mistake here... What am I doing wrong?

2 Answers 2

3

In the conditions, don't close variables in the double-braces "{{ }}". The variables are expanded in the conditions by default. For example, test it

    - debug:
        msg: Fail
      when: jdk_new_version == jdk_old_vers.stdout
      vars:
        jdk_new_version: 1.8.0_332
        jdk_old_vers:
          stdout: 1.8.0_332

gives

  msg: Fail

For advanced options see Comparing versions. For example, test the new version is not lower or equal to the old version

    - debug:
        msg: Fail
      when: jdk_new_version is version(jdk_old_vers.stdout, '<=')
2

If you want to end playbook when condition meets


- meta: end_play
  when:
    -  jdk_new_version == jdk_old_vers.stdout
  vars:
    jdk_new_version: 1.8.0_332
    jdk_old_vers:
        stdout: 1.8.0_332

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .