Ansible if file does not exist

Create a properties file with Ansible, not adding the property if the value does not exist

I'm trying to create a properties file with mandatory and optional properties in Ansible with templates.

I want any essentially static string (any optional property name) to be displayed only if the associated property value is present (from an Ansible variable)

Right now my Ansible template looks like this:

However, the application itself has hard-coded values ​​for any optional properties. I just want a line "property = value" to be written to the property file from the template if the associated variable is present.

So if you have environment X (group_vars)

continue with the template above

but not

to adjust

My desired output of the template in the provided file is:

There must be a better solution for this in Ansible. The closest I found Ansible filtering, I couldn't find anything related to showing / hiding template text there.

Final note: I have a hacky backup solution - I take each line of and make the variable equal to the entire string. However, this feels like the point of a template with so much static text stored in variables is completely missed.


Firstly, this is not an Ansible problem, it is a question of how to work with Jinja2 template language (and as a strictly programming question, it should be asked about StackOverflow and not ServerFault).

Go to the Jinja2 documentation in the instruction. There you will find an exact example for your case:

The statement in Jinja is comparable with the Python statement. In the simplest form, you can use it to test if a variable is defined, not empty and not false.

Here is an example of how you should customize it: