2

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.

closed as off-topic by peterh, quadruplebucky, mdpc, MadHatter, Ward Jun 21 '17 at 1:24

  • This question does not appear to be about server, networking, or related infrastructure administration within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

3

Firstly, this is not an Ansible problem, it's a question how to use Jinja2 templating language (and as a strictly programming question, it should be asked on StackOverflow not ServerFault).

Head to Jinja2 documentation on if statement and you will find an exact example for your case:

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

Here's an example how you should customise it:

{% if OptProperty2_value %}OptProperty2={{ OptProperty2_value }}{% endif %}
  • Thanks! That's precisely what I was looking for, and I'm able to build my solution with it. (My search scope was limited to ansible, and being reasonably new to ansible I didn't really realize I'd need to look outside ansible and into jinja) – Ryan Jun 15 '17 at 18:01
  • @techraf in case you didn't see or ignored my chat message, here's your answer. – terdon Jun 22 '17 at 19:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.