# Setting Variables Conditionally

**URL:** <https://forum.ansible.com/t/setting-variables-conditionally/25199>\
**Category:** Ansible Project\
**Created:** [August 8, 2017, 3:08am UTC](https://forum.ansible.com/t/setting-variables-conditionally/25199 "2017-08-08T03:08:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ryan1](https://avatars.discourse-cdn.com/v4/letter/r/3da27b/32.png) [@Ryan1](https://forum.ansible.com/u/Ryan1)\
**Post date:** [August 8, 2017, 3:08am UTC](https://forum.ansible.com/t/setting-variables-conditionally/25199/1 "2017-08-08T03:08:40Z")

</div>

I need to set some variables that are the same no matter the client, and other variables need to be set conditionally based on values from Ansible facts. Basically I need an if/else case statement. What is the correct way to do this?

Some simple examples can be found here ([http://docs.ansible.com/ansible/latest/playbooks\_conditionals.html#conditionals](http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#conditionals)) but this doesn’t cover else conditions, and if I remove the second instance of VAR4, and put in condition that is not met, it still sets VAR4, when the match doesn’t exist, so it seems like the “when” is not being evaluated.

---

<div class="post-metadata">

**Author:** ![benno\_joy](https://avatars.discourse-cdn.com/v4/letter/b/73ab20/32.png) [@benno\_joy](https://forum.ansible.com/u/benno_joy)\
**Post date:** [August 8, 2017, 4:58am UTC](https://forum.ansible.com/t/setting-variables-conditionally/25199/2 "2017-08-08T04:58:00Z")

</div>

some ways to do this would be

using filters (clean way)  
&nbsp;&nbsp;&nbsp;set\_fact:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;myvar: "{{ (ansible\_os\_family == 'RedHat') | ternary(100,200) }}"

or same thing via jinja conditionals

{{ 100 if ansible\_os\_family == 'RedHat' else 200 }}

with some 'or's

&nbsp;&nbsp;&nbsp;&nbsp;{{ 100 if ansible\_os\_family == 'RedHat' or ansible\_user\_id ==  
'vagrant' else 200 }}

---

<div class="post-metadata">

**Author:** ![Ryan1](https://avatars.discourse-cdn.com/v4/letter/r/3da27b/32.png) [@Ryan1](https://forum.ansible.com/u/Ryan1)\
**Post date:** [August 8, 2017, 7:50am UTC](https://forum.ansible.com/t/setting-variables-conditionally/25199/3 "2017-08-08T07:50:49Z")

</div>

This seems to be working, but is there a more readable way to write this?

size: “{{ 300 if 'string1’ in ansible\_fact or ‘string\_2’ in ansible\_fact or ‘string\_3’ in ansible\_fact or ‘string\_4’ in ansible\_fact else 100 if ‘string\_5’ in ansible\_fact or ‘string\_6’ in ansible\_fact or ‘string\_7’ in ansible\_fact else 200 if ‘string\_8’ in ansible\_fact }}”
