Home > other >  ansible - how to define var's value depending on ansible_facts
ansible - how to define var's value depending on ansible_facts

Time:10-31

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?

CodePudding user response:

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

CodePudding user response:

The reason why you always end up with version as "1.8.0", is because your variables definition is a list and when conditionals are not doing anything there.

When java_open_jdk_version_major is evaluated first, its value is "8", but another definition is found below, which is "1.8.0", and lastly evaluated value wins.

Another way to achieve this, and ensure that appropriate versions are set for the respective Distribution (CentOS and Ubuntu) is to use a pre_tasks section, like so:

- hosts: all

  pre_tasks:
    - name: set JDK major version for CentOS
      set_fact:
        java_open_jdk_version_major: "1.8.0"
      when: ansible_distribution == 'CentOS'

    - name: set JDK major version for Ubuntu
      set_fact:
        java_open_jdk_version_major: "8"
      when: ansible_distribution == 'Ubuntu'

  roles:
    - name: jdk
  • Related