Ansible, set_fact using if then else statement

倖福魔咒の 提交于 2019-12-03 15:57:45

Firstly, dictionaries in YAML are not ordered (and the syntax used by Ansible here is a YAML dictionary), so you have no guarantee Ansible would first set jm_env before proceeding to l_env -- you need to split the assignment into two tasks.

Secondly, your test expressions are incorrect -- '{{jm_env}}==Develop' is a string because it is quoted; and testing if 'string' will always evaluate to true (this is the direct reason you always get d in the output).

Use:

- name: Set the jm_env
    set_fact:  
      jm_env: "{{lookup('env', 'Environment')}}"

- name: Set the l_env
    set_fact:  
      l_env: "{% if jm_env=='Develop' %}d{% elif jm_env=='Staging'%}s{% else %}p{% endif %}"

One of the simple way to set fact based condition example as follows:

  - name: Set facts for delete operation results
    set_fact:
        tr_result: "{{ '{\"status\": \"SUCCESS\"}' if (op_result['output'] == 'Deleted') else '{\"status\" : \"FAILED\"}' }}"

Note: Assume op_result is a dict & already defined.

Code has been tested and working well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!