Syntax errors with Jinja2 control structures in tasks file

9 views
Skip to first unread message

Alexander Z

unread,
Jun 4, 2020, 4:45:26 PM6/4/20
to Ansible Project
Hi Ansible community,

I am observing syntax error on attempt to use Jinja2 control structures in the tasks file:

Code
/opt/ansible/roles/network/tasks/network.yml:
{% if publicavailable|default(False) == False and public|default("") == "" and datacenter != "XXX" and datacenter != "YYY" %}
{% set private_interface = ansible_default_ipv4.interface %}
{% else %}
{% set private_interface = ansible_default_ipv4.interface|regex_replace('\d+','')|string + (ansible_default_ipv4.interface|regex_replace('\D+','')|int+1)|string %}
{% endif %}
- name: alias interface on private servers
  template:
    src: if_internal_eth.j2
    dest: /etc/network/interfaces.d/if_{{ private_interface }}_0.cfg
    owner: root
    group: root
    mode: 0644
  when: 'datacenter != "XXX" and datacenter != "YYY" and vlan_prefix2|default("") != ""'

Error
fatal: [host.domain.tld]: FAILED! => {"reason": "Syntax Error while loading YAML.
  found character that cannot start any token
The error appears to have been in /opt/ansible/roles/network/tasks/network.yml: line 52, column 2, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:

{% if publicavailable|default(False) == False and public|default(\"\") == \"\" and datacenter != \"XXX\" and datacenter != \"YYY\" %}
 ^ here
"}

Versions
ansible 2.5.10
python version = 2.7.12
Ubuntu 16.04.3 LTS


Kindly advise!
Thank you,
Alex

Brian Coca

unread,
Jun 4, 2020, 5:04:37 PM6/4/20
to Ansible Project
That is because that is not a feature of Ansible.

Ansible parses the files using a YAML loader, then it does use jinja2
internally for templating, but only on SOME of the values in the data
structure returned by YAML.

----------
Brian Coca

Alexander Z

unread,
Jun 5, 2020, 10:53:15 AM6/5/20
to Ansible Project
Hi Brian,

Thank you for the prompt reply.
Is there is any documentation describing that limitation? 
For example it renders correctly some variables inside {{ ... }} but does not allows to use control structures {% ... %} to define those variables.
Kindly advise!

Thank you,
Alex
Reply all
Reply to author
Forward
0 new messages