Conditions based on dict (environmental variable)

If I check a remote dict item (inside a role/playbook), that may not be present like:

debug msg="JAVA_HOME= {{ ansible_env.JAVA_HOME }} "

Then I get the following exception:

TASK: [java-noinstall | debug msg="JAVA_HOME= {{ ansible_env.JAVA_HOME }} "] ***
fatal: [vm] => One or more undefined variables: ‘dict object’ has no attribute ‘JAVA_HOME’

FATAL: all hosts have already failed – aborting

I have two workarounds:

  1. create a computed variable in /vars/main.yaml:

actual_java_home: “{{ ansible_env.JAVA_HOME if (‘JAVA_HOME’ in ansible_env) else ‘’}}”

…and use that instead as a condition inside the role/playbook:

debug msg="JAVA_HOME= {{ actual_java_home }} "

  1. check once and then register a new variable based on the result:
  • name: First conditional task
    when: {{ ansible_env.JAVA_HOME if (‘JAVA_HOME’ in ansible_env) else ‘’}}
    register: change_it

action: …

  • name: Second conditional task
    when: not change_it|skipped

action: …

Is there a better solution for that? Or those are the best practices?