Conditional control structure in Jinja2 templates
Ansible uses Jinja2 as a template engine. Hence, it would be useful for us to understand Jinja2 control structures in addition to the ones supported by Ansible tasks. Jinja2's syntax encloses the control structures inside the {% %}
blocks. For conditional control, Jinja2 uses the familiar if
statements, which have the following syntax:
{% if condition %} do_some_thing {% elif condition2 %} do_another_thing {% else %} do_something_else {% endif %}
Updating the MySQL template
The template that we created earlier to generate the my.cnf
file assumes that all the variables referred in it are defined somewhere. There is a chance that this is not always the case, which could result in errors while running Ansible. Could we selectively include configuration parameters in the my.cnf
file? The answer is yes. We could check whether a variable is defined and only then, we will add it to the file, as follows:
#filename: roles/mysql/template...