ansible jinja2 template delimiters failed if using 'when'

Viewed 191

I have this code, where the first task fails and the second task produces the following warning:
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ VRF }} == 17

I am assuming this warning and the failure of the first task are happening for the same reason. From what I understand, the variables are different types. How do I fix this?

---
- name: PE_CE
  hosts: localhost

  tasks:

  - include_vars: /opt/netsec/ansible/orchestration/capabilities/PE_CE/PE_CE_1.yml
  
  - name: Build PE config Cisco
    template:
      src=/opt/netsec/ansible/orchestration/cisco_templates/PE_CE_CISCO_config_PE.j2
      dest=/opt/netsec/ansible/orchestration/config_outputs/new/{{PE_HOSTNAME}}
    when: "{{ PX_HOSTNAME }} == None"

  - name: Build CE config Cisco
    template:
      src=/opt/netsec/ansible/orchestration/cisco_templates/PE_CE_CISCO_config_CE.j2
      dest=/opt/netsec/ansible/orchestration/config_outputs/new/{{CE_HOSTNAME}}
    when: "{{ VRF }} == 17"

What I really want to do is when: "{{ VRF }} == 17" and "{{ PX_HOSTNAME }} == None", or something like {{ PX_HOSTNAME }}|length < 1"

1 Answers

You do not need {{ and }} with when. Do it like this:
when: PX_HOSTNAME == "None" and when: VRF == "17"

Here is some documentation

when: PX_HOSTNAME == "None" will check if PX_HOSTNAME contains the string "None".
If you want to run the task if it is empty, do when: not PX_HOSTNAME or if you want to run the task it it is not empty, do when: PX_HOSTNAME.

You can use the length as well: when: PX_HOSTNAME|length > 0

Related