# conditionally assign value to variable

**URL:** <https://forum.ansible.com/t/conditionally-assign-value-to-variable/19723>\
**Category:** Ansible Project\
**Created:** [November 10, 2015, 9:34am UTC](https://forum.ansible.com/t/conditionally-assign-value-to-variable/19723 "2015-11-10T09:34:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![r.grosmann](https://avatars.discourse-cdn.com/v4/letter/r/43a26b/32.png) [@r.grosmann](https://forum.ansible.com/u/r.grosmann)\
**Post date:** [November 10, 2015, 9:34am UTC](https://forum.ansible.com/t/conditionally-assign-value-to-variable/19723/1 "2015-11-10T09:34:35Z")

</div>

hello group,

I want to do something which should be quite easy, but I cannot find out exactly how I should do it.

I want variable usedir to have the name of directory {{currentdir}}/rails if it exists, else I want to have it the name of directory {{prevdir}}/rails if that directory exists, else I want it to be the empty string.

I have two registered variables with the stat value of the two directories with names curstat and prevstat. How can I use them to set variable userdir?

Thanks for your help.  
Ruud

---

<div class="post-metadata">

**Author:** ![r.grosmann](https://avatars.discourse-cdn.com/v4/letter/r/43a26b/32.png) [@r.grosmann](https://forum.ansible.com/u/r.grosmann)\
**Post date:** [November 10, 2015, 1:52pm UTC](https://forum.ansible.com/t/conditionally-assign-value-to-variable/19723/2 "2015-11-10T13:52:32Z")

</div>

I found a solution, although it’s maybe not the best. In case someone is interested:

tasks:

- name: check currentdir  
stat: path={{currentdir}}/rails  
register: curstat

- name: check prevdir  
stat: path={{prevdir}}/rails  
register: prevstat

- name: set variable  
set\_fact: userdir=‘’

- name: next prev  
when: prevstat.stat.exists  
set\_fact: userdir={{prevstat.stat.path}}

- name: next current  
when: curstat.stat.exists  
set\_fact: userdir={{curstat.stat.path}}
