I am trying to assign a variable to a directory only if it exists, else assign a default value.
#java
java_root: "{{ root_dir }}/java"
JAVA_HOME: "{{ java_root }}/jdk-default.version"
If a given newer JDK version is installed (given the directory name), I 'd like to assign the variable JAVA_HOME
to another value.
In pseudo code
if directory exist "{{ java_root }}/jdk-x.0"
JAVA_HOME: "{{ java_root }}/jdk-x.0"
else
JAVA_HOME: "{{ java_root }}/jdk-default.version"
I read about Ansible module stat
but I prefer to avoid it. Not sure if the machine has module stat
installed.
There is a way to avoid the Ansible module stat
It is with find .
Then the result is stored in variable jdks_dirs
with register.
tasks:
- name: Check if the newer JDK version directory exists
find:
paths: "{{ java_root }}"
patterns: "jdk-x.0"
file_type: directory
register: jdk_dirs
Then the conditions are defined with keyword when
# if the directory exists
- name: Set JAVA_HOME based on directory existence
set_fact:
JAVA_HOME: "{{ java_root }}/jdk-x.0"
when: jdk_dirs.matched > 0
# else if the directory doesn't exist
- name: Set JAVA_HOME to default if newer JDK version directory does not exist
set_fact:
JAVA_HOME: "{{ default_java_home }}"
when: jdk_dirs.matched == 0
# whatever the condition, print the result
- name: Debug JAVA_HOME
debug:
msg: "JAVA_HOME is set to {{ JAVA_HOME }}"
Note the when conditions must be exclusive. There is no such a thing as else condition in Ansible.
There is another way to else condition.