I am trying to build a property file with mandatory and optional properties in Ansible with templating.
I want each essentially-static string (each optional property name) to show up only if the associated property value exists (from an Ansible variable)
Right now, my ansible template looks like this:
# Mandatory Properties
ManProperty1={{ ManProperty1_value }}
ManProperty2={{ ManProperty2_value }}
# Optional Properties
OptProperty1={{ OptProperty1_value }}
OptProperty2={{ OptProperty2_value }}
But the application itself has hardcoded values for all the optional properties, and I only want a "property=value" line to get written to the properties file from the template if the associated variable exists.
So continuing with the template above, if I set for environment X (group_vars)
ManProperty1_value = myManValue1
ManProperty2_value = myManValue2
OptProperty1_value = myOptValue1
but do not set
OptProperty2_value
My desired output of the template to the deployed file is:
# Mandatory Properties
ManProperty1=myManValue1
ManProperty2=myManValue2
# Optional Properties
OptProperty1=myOptValue1
There must be a better solution in Ansible to this. The closest I found was ansible filtering, but I couldn't find anything in there related to show/hide of template text.
Final note: I do have a hackish backup solution - I take each line of property=value
and make the variable equal the entire string. But this feels like it's completely missing the point of a template with so much static text stored in variables.