Ansible, set_fact using if then else statement
Asked Answered
N

2

19

I am trying to set a variable in Ansible with set_fact at runtime based upon another variable. If uses first value no matter what the actual value is. Here is my code example:

- name: Global_vars - get date info
    set_fact:  
      jm_env: "{{lookup('env', 'Environment')}}"
      l_env: "{% if '{{jm_env}}==Develop' %}d{% elif '{{jm_env}}==Staging'%}s{% else %}p{% endif %}"

l_env is d no matter what jm_env is set.

Nitwit answered 21/3, 2017 at 18:52 Comment(0)
C
21

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 %}"
Centuplicate answered 21/3, 2017 at 21:36 Comment(2)
that worked. i didn't realize the order could be the issueNitwit
@Nitwit Please have a look at the Help Center: do not add a comment on your question or on an answer to say "Thank you"..Centuplicate
C
11

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.

Counterintelligence answered 4/5, 2018 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.