# Conditions based on dict (environmental variable)

**URL:** <https://forum.ansible.com/t/conditions-based-on-dict-environmental-variable/17720>\
**Category:** Ansible Project\
**Created:** [March 11, 2015, 4:41pm UTC](https://forum.ansible.com/t/conditions-based-on-dict-environmental-variable/17720 "2015-03-11T16:41:51Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bence\_Takacs](https://avatars.discourse-cdn.com/v4/letter/b/c6cbf5/32.png) [@Bence\_Takacs](https://forum.ansible.com/u/Bence_Takacs)\
**Post date:** [March 11, 2015, 4:41pm UTC](https://forum.ansible.com/t/conditions-based-on-dict-environmental-variable/17720/1 "2015-03-11T16:41:51Z")

</div>

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?
