Interview Prep/Ansible/Jinja2, Conditionals and Loops

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.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops