- roles - consul - vars/main.yml 

In main.yml use:

 consul_is_server: {{ true if consul_server is defined else false }} 

playbook:

 - hosts: consul-server roles: - consul vars: consul_server: true 

Mistake:

 consul_is_server: {{ "true" if consul_server is defined else "false" }} ^ We could be wrong, but this one looks like it might be an issue with missing quotes. Always quote template expression brackets when they start a value. For instance: with_items: - {{ foo }} Should be written as: with_items: - "{{ foo }}" 

Did so:

 consul_is_server: > {{ true if consul_server is defined and consul_server==true else false }} 

But then consul_is_server will be the string: "False" or "True." And then in the templates you have to cast in bool :

 "server": {{ "true" if consul_is_server |bool else "false" }} 

Can I vars write the conditions check in vars so that I don’t have to do it in the template later?

  • one
    "{{ true if consul_server is defined else false }}" ? - Nick Volynkin
  • @NickVolynkin there is only a check on defined , it is necessary that it still be true - Suvitruf

1 answer 1

Use ternary

Documentation: http://docs.ansible.com/playbooks_filters.html

Example:

 --- # https://ru.stackoverflow.com/questions/470202/ - name: https://ru.stackoverflow.com/questions/470202/ hosts: test vars: str1: "asdf1" str2: "asdf2" cond1: True cond2: False result1: "{{ cond1 | ternary(str1, str2) }}" result2: "{{ cond2 | ternary(str1, str2) }}" tasks: - name: debug result1 debug: msg="{{ result1 }}" connection: local - name: debug result2 debug: msg="{{ result2 }}" connection: local 

Conclusion:

 $ ansible-playbook -i hosts_debug sample_ru_470202.yml PLAY [collect info] ************************************************************ TASK [setup] ******************************************************************* ok: [myserver1] TASK [debug result1] *********************************************************** ok: [myserver1] => { "msg": "asdf1" } TASK [debug result2] *********************************************************** ok: [myserver1] => { "msg": "asdf2" } PLAY RECAP ********************************************************************* myserver1 : ok=3 changed=0 unreachable=0 failed=0 

PS A more complex example here asked today: Compound variable in a ternary j2-template ansible

  • In general, I slightly modified the version from Nick Volynkin, but for years ago this one took: D - Suvitruf