Search code examples
ansiblejinja2

Conditions in J2 templates (Ansible)


I use this syntax in my Jinja template to print the string "foobar" if the content of the custom variables cannot be parsed, and this works well:

{{ hostvars[h]['myvar'][0]['myothervar'] | default('foobar') }}

Now, I'd like to print the content of the above custom variables if Ansible cannot reach the target machine to fetch the number of CPUs, but this syntax does not work:

{{ hostvars[h]['ansible_processor_vcpus'] | hostvars[h]['myvar'][0]['myothervar'] }}

It throws instead an error:

AnsibleError: template error while templating string: expected token
'end of print statement', got '['.   

What would the correct syntax be?


Solution

  • The | operator is not "alternation" (this | that does not mean this OR that). It's more like a shell pipeline -- it passes the output of the expression on the left to the filter on the right.

    Your second expression is not a filter.

    You could use the default filter, just like in your first example:

    {{
      hostvars[h]['ansible_processor_vcpus'] |
      default(hostvars[h]['myvar'][0]['myothervar'])
    }}