Show a template with a loop and a conditional, and how it is deployed.
BeginnerConceptJinja2, Conditionals and Loops
Answer
# {{ ansible_managed }}
server {
listen {{ nginx_port | default(80) }};
server_name {{ server_names | join(' ') }};
{% if nginx_tls_enabled | default(false) %}
ssl_certificate {{ nginx_cert_path }};
{% endif %}
}
- ansible.builtin.template:
src: site.conf.j2
dest: /etc/nginx/conf.d/site.conf
owner: root
mode: "0644"
notify: Reload nginx
Templates live in the role's templates/ directory. For files that are complete configs, add validate: (for example validate: nginx -t -c %s) so a broken render never replaces a working file.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?BeginnerHow do you combine several conditions?Beginner