ansible – how to define var’s value depending on ansible_facts

I’m writing an ansible playbook for installing jdk.

The logic is to use version 8 if the system is “Ubuntu”, but 1.8.0 if it is “CentOS”.

following is my code:

- hosts: all
  vars:
    - java_open_jdk_version_major: 8
      when: ansible_distribution == 'Ubuntu'
    - java_open_jdk_version_major: 1.8.0
      when: ansible_distribution == 'CentOS'
  roles:
    - name: jdk

In this way, the “java_open_jdk_version_major” always becomes 1.8.0.

How to define variables in this case?

Answer

you do something like this:

- hosts: all
  vars:
    - java_open_jdk_version_major: "{{ '1.8.0' if ansible_distribution == 'CentOS' else '8' }}"
  roles:
    - name: jdk