Search code examples
ansiblenulljinja2defaultliterals

How to render a literal 'null' in Jinja2 Template


I'm working on an ansible role that allow users to interact with a REST API. I create json.j2 templates that allow me to build the message payload and eventually submit. One of the fields expects either a string value ("") or null.

{
  "value": "{{ example.value | default(null, true) }}"
}

This doesn't work and I get this error:

The task includes an option with an undefined variable. The error was: 'null' is undefined

I need that null value and I need to come in as the default value if no other value is provided.
How do I do this?


Solution

  • As pointed in the comments, null has no meaning in Python, None is the Python representation of what your are looking for.

    Now, if you want to convert this to a JSON value, then there is a to_json filter in Ansible, so:

    '{ "value": {{ example.value | default(None, true) | to_json }} }'
    

    Would end up as:

    { "value": null }