title: How to write dynamic variable in Ansible playbook
body: <p>Based on <code>extra vars</code> parameter I Need to write variable value in <code>ansible playbook</code></p>
  
  <pre><code>ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3"
  </code></pre>
  
  <p>If only <strong>param1</strong> passed</p>
  
  <pre><code>myvariable: 'param1'  
  </code></pre>
  
  <p>If only <strong>param1,param2</strong> passed</p>
  
  <pre><code>myvariable: 'param1,param2' 
  </code></pre>
  
  <p>If <strong>param1,param2,param3</strong> are passed then variable value will be</p>
  
  <pre><code>myvariable: 'param1,param2,param3' 
  </code></pre>
  
  <p>When I try to create variable dynamically through template then my playbook always takes previous variable value. But inside  <code>dest=roles/myrole/vars/main.yml</code> its writing correct value. </p>
  
  <p>What I make a try here </p>
  
  <pre><code>- hosts: local
    user: roop
    gather_facts: yes
    connection: local
  
    tasks: 
  
    - template: src=roles/myrole/templates/myvar.j2 dest=roles/myrole/vars/main.yml
  
    - debug: var=myvariable
  
    roles:
          - { role: myrole }
  </code></pre>
  
  <p>So inside <strong>myrole</strong> directory I have created <code>template</code> and <code>vars</code></p>
  
  <pre><code>- roles
    - myrole
      - vars/main.yml
      - templates/myvar.j2 
  </code></pre>
  
  <p><strong>templates/myvar.j2</strong> </p>
  
  <pre><code>{% if param1 is defined and param2 is defined and param3 is defined %}
    myvariable: 'param1,param2,param3'
  {% elif param1 is defined and param2 is defined %}
    myvariable: 'param1,param2'
  {% elif param1 is defined %}
    myvariable: 'param1'
  {% else %}
    myvariable: 'default-param'
  {% endif %} 
  </code></pre>
  
  <p>As I know if only two condition then I can do this using <code>inline expression</code> like below</p>
  
  <pre><code>{{ 'param1,param2' if param1 is defined and param2 is defined else 'default-param' }}
  </code></pre>
  
  <p><code>&lt;do something&gt; if &lt;something is true&gt; else &lt;do something else&gt;</code></p>
  
  <p>Is it possible <code>if - elif - else</code> in <code>inline expression</code> like above. Or any other way to assign value dynamically in ansible playbook?  </p>