How to write dynamic variable in Ansible playbook


Based on extra vars parameter I Need to write variable value in ansible playbook

If only param1 passed

If only param1,param2 passed

If param1,param2,param3 are passed then variable value will be

When I try to create variable dynamically through template then my playbook always takes previous variable value. But inside dest=roles/myrole/vars/main.yml its writing correct value.

What I make a try here

So inside myrole directory I have created template and vars


As I know if only two condition then I can do this using inline expression like below

<do something> if <something is true> else <do something else>

Is it possible if - elif - else in inline expression like above. Or any other way to assign value dynamically in ansible playbook?


I am sure there is a smarter way for doing what you want but this should work:

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

Leave a Reply