Since Module 3, all of Aurora Store's configuration has been written with ansible.builtin.copy and a content: | block: the nginx site, the PostgreSQL parameters, the home page, the connection details… For five-line files that's convenient, but it has clear limits: the configuration file is buried inside the YAML, with two extra levels of indentation; there's no reasonable way to repeat a line for each server or to include a block only when a condition is met; and anyone who wants to review the nginx configuration has to read an Ansible task. The standard solution is templates: text files with Jinja2 markup that Ansible fills in with each host's variables. In this lesson you'll learn the template module, Jinja2 syntax (expressions, conditionals, loops, comments and whitespace control), the ansible_managed variable and the validate and backup parameters, and you'll migrate all the configuration of the Aurora roles to templates. You'll also manage two complete files that you didn't control until now: nginx.conf and pg_hba.conf.
Contents
- From
copywithcontent:to templates - The
ansible.builtin.templatemodule - Where templates live: the
templates/directory - Jinja2 syntax:
{{ }},{% %}and{# #} - Variables and expressions
- Conditionals
- Loops
- Whitespace control
ansible_managed: the header of managed filesvalidateandbackup- Practice: a literal migration to templates
- Practice:
nginx.confand a site with optional load balancing - Practice: a complete
pg_hba.conf - Verifying and saving the work
- From
copy with content: to templates
copy with content: to templatesCompare the two ways of publishing the PostgreSQL parameters:
| Aspect | copy + content: |
template + .j2 file |
|---|---|---|
| Where the configuration lives | Inside the task, in YAML | In its own file, with the service's syntax |
| Variables | Yes ({{ }}) |
Yes ({{ }}) |
| Conditionals and loops | Very awkward | Natural ({% if %}, {% for %}) |
| Comments that don't reach the server | No | Yes ({# #}) |
| Syntax highlighting in the editor | YAML's | The service's (or Jinja's) |
| Review in git | Mixed in with the tasks | A clean diff of the file |
| When to use it | One- or two-line files | Any real configuration file |
copy with content: doesn't go away: it's still useful for minimal files (the static pages in aurora_app_static_pages, for example). And copy with src: is still the right choice for files without variables, such as gzip.conf: if there's nothing to fill in, there's no reason for a template.
- The
ansible.builtin.template module
ansible.builtin.template moduletemplate is used almost exactly like copy:
- name: Configure the PostgreSQL parameters
ansible.builtin.template:
src: parameters.conf.j2
dest: /etc/postgresql/16/main/conf.d/aurora.conf
owner: postgres
group: postgres
mode: "0644"
notify: Restart PostgreSQLWhat happens when it runs:
flowchart LR
A[parameters.conf.j2<br/>on the control node] --> B[Jinja2 renders it<br/>with the host's variables]
B --> C[Text result]
C --> D{Same as the file<br/>on the server?}
D -- Yes --> E[ok]
D -- No --> F[Copy to the server<br/>changed + notify]
- The template is rendered on the control node, with each host's variables (inventory, facts, role variables…). That's why each server can receive a different result.
- The result is compared with the file on the server: if it's identical,
ok; if not, it's copied and the task returnschanged. - With
--check --diffyou see the exact change that would be applied, line by line.
Main parameters:
| Parameter | What it's for |
|---|---|
src |
Template (in a role, relative to templates/) |
dest |
Path of the file on the server |
owner, group, mode |
Owner and permissions, as in copy |
validate |
Command that validates the file before putting it in place (%s = path of the temporary file) |
backup |
Keeps a copy of the previous file if it changes |
trim_blocks, lstrip_blocks |
Whitespace control (section 8) |
force |
If false, it only creates the file if it doesn't exist |
- Where templates live: the
templates/ directory
templates/ directoryIn Lesson 4.3 you saw how a role looks up relative paths. For template, a relative path in src is looked up first in the role's templates/ directory. The convention is:
- A role's templates go in
roles/<role>/templates/. - They have the
.j2extension (for Jinja2), added to the name the file will have:nginx.conf.j2,pg_hba.conf.j2,index.html.j2. - If the name on the server depends on a variable (like the nginx site, which is called
{{ nginx_site_name }}), the template gets a generic name that describes its function:site.conf.j2.
By the end of the lesson, the Aurora roles will have these templates:
roles/
├── nginx/templates/{nginx.conf.j2, site.conf.j2}
├── postgresql/templates/{parameters.conf.j2, pg_hba.conf.j2}
├── aurora_app/templates/{index.html.j2, db.conf.j2}
└── common/templates/{motd.j2, facts.fact.j2} ← exercise 1
- Jinja2 syntax:
{{ }}, {% %} and {# #}
{{ }}, {% %} and {# #}A template is normal text with three kinds of markup:
| Markup | Name | What it does | Example |
|---|---|---|---|
{{ ... }} |
Expression | Replaced by the value | port = {{ postgresql_port }} |
{% ... %} |
Statement | Controls the template: conditions, loops, assignments | {% if nginx_upstream_servers %} |
{# ... #} |
Comment | Disappears from the result | {# Reviewed by Alex #} |
Everything that isn't inside markup is copied as is. This matters with configuration files that use braces, like nginx: server { and } aren't Jinja markup (only {{, {% and {# are), so they're copied without problems. nginx variables such as $host or $uri mean nothing to Jinja either.
If you ever need to write {{ literally in the result (for example, in a template for another tool that also uses that syntax), wrap that fragment in {% raw %} ... {% endraw %}.
- Variables and expressions
Inside {{ }} you can use any variable available to the host, with the same notation as in playbooks:
Server: {{ inventory_hostname }}
System: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
Database: {{ aurora_app_db_name }}
First client: {{ postgresql_hba_clients[0] }}You can also use expressions and some basic filters (Lesson 5.3 covers them in depth):
| Expression | Result | What for |
|---|---|---|
{{ nginx_worker_connections * 2 }} |
2048 |
Arithmetic |
{{ aurora_env | upper }} |
LAB |
Uppercase |
{{ common_packages | join(', ') }} |
htop, curl, vim, tree |
Joining a list |
{{ postgresql_hba_clients | length }} |
2 |
Number of elements |
{{ nginx_server_name | default('_') }} |
Its value, or _ if it isn't defined |
Default value |
Besides the host's variables, a template has a few variables of its own provided by the module: ansible_managed (section 9), template_path (path of the template), template_host (name of the control node) and template_run_date. Use them carefully: the date, for example, would make the file change on every run.
- Conditionals
{% if postgresql_hba_method == 'trust' %}
# WARNING: passwordless authentication. Lab use only.
{% elif postgresql_hba_method == 'md5' %}
# Legacy method: consider migrating to scram-sha-256.
{% else %}
# Authentication with scram-sha-256.
{% endif %}- Conditions use the same syntax as
when(Lesson 3.6): comparisons,and/or/not,in, tests such asis defined. - Unlike in
when, here variables go without{{ }}because you're already inside Jinja markup. - An empty list or dictionary is false:
{% if nginx_upstream_servers %}means "if there's any server".
- Loops
{% for client in postgresql_hba_clients %}
host aurora aurora {{ client }}/32 scram-sha-256
{% endfor %}Inside a for you have the special variable loop:
| Variable | Value |
|---|---|
loop.index |
Iteration number, starting at 1 |
loop.index0 |
Iteration number, starting at 0 |
loop.first / loop.last |
True on the first / last iteration |
loop.length |
Total number of elements |
Two more forms you'll use in Aurora:
{# Iterating over a dictionary: key and value #}
{% for address, weight in nginx_upstream_servers.items() %}
server {{ address }}:80 weight={{ weight }};
{% endfor %}
{# else: used if the list is empty #}
{% for client in postgresql_hba_clients %}
host ... {{ client }}/32 ...
{% else %}
# No remote clients authorized.
{% endfor %}
- Whitespace control
{% %} markup takes up a line in the template, but it shouldn't leave empty lines in the result. Jinja has two options to control this, and the template module sets them like this by default:
| Option | Default value in template |
Effect |
|---|---|---|
trim_blocks |
true |
Removes the newline that follows a {% %} tag |
lstrip_blocks |
false |
If it were true, it would remove the spaces before a {% %} tag on its line |
With these values, a tag written at the beginning of the line disappears completely:
If nginx_port is 80, the result is exactly server { and listen 80; one after the other, with no blank lines.
But if you indent the tag to make the template more readable, the preceding spaces stay (because lstrip_blocks is false), and the result would have a line of spaces. You have three solutions:
- Write the
{% %}tags in column 0 (what Aurora does: it's the most predictable). - Enable
lstrip_blocks: truein the task, or on the first line of the template with#jinja2: lstrip_blocks: True. - Use the Jinja dash:
{%-removes the preceding whitespace and newlines, and-%}the following ones. It works the same way in{{- -}}and{#- -#}.
Here -#} swallows the newline that follows the comment, so the resulting file starts directly with <!DOCTYPE html>. Be careful with the dash: it swallows all adjacent whitespace and newlines, and used carelessly it glues together lines that should be separate. When in doubt, check the result with --check --diff.
ansible_managed: the header of managed files
ansible_managed: the header of managed filesSince Module 3, every Aurora configuration file has started with # Managed by Ansible (aurora-infra). Do not edit by hand.. Ansible has a variable designed for this, ansible_managed, available in templates. Its default value is Ansible managed, and it's configured in ansible.cfg. Add to [defaults]:
# Text of the ansible_managed variable (header of the files generated from templates).
ansible_managed = Managed by Ansible (aurora-infra). Do not edit by hand.And in every template, the first line will be:
Advantages: the text lives in a single place, and any role you use (including third-party ones, in Module 6) will add the same header. Details:
- You supply the comment character (
#in nginx and PostgreSQL), because each format has its own. There's also thecommentfilter ({{ ansible_managed | comment }}), which generates a multi-line comment block. - Don't put dates or the user in
ansible_managed: the file would change on every run and notify handlers for no reason. ansible_managedonly exists inside templates: in acopywithcontent:it isn't defined.
validate and backup
validate and backup10.1. validate
validate specifies a command that checks the file before installing it. Ansible writes the result to a temporary file on the server, runs the command replacing %s with the path of the temporary file and, only if it succeeds, moves it to its destination:
- name: Publish the main nginx configuration
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
validate: nginx -t -c %sIf validation fails, the task fails with the command's output, and the original file isn't touched: the server keeps its good configuration. Common examples:
| File | validate |
|---|---|
/etc/nginx/nginx.conf |
nginx -t -c %s |
/etc/sudoers.d/* |
visudo -cf %s |
/etc/ssh/sshd_config |
/usr/sbin/sshd -t -f %s |
/etc/haproxy/haproxy.cfg |
haproxy -c -f %s |
As you saw in Lesson 5.1, validate only works for files that can be validated on their own. The nginx site is a fragment, so its validation is still done by the handlers (nginx -t before reloading). With the complete nginx.conf it does work, with one condition: its include directives must use absolute paths, because nginx resolves relative ones from the directory of the file being validated, which here is a temporary one.
PostgreSQL doesn't have a validator for a standalone pg_hba.conf. After reloading, you can query the pg_hba_file_rules view, which shows each rule and, if there is one, its error column.
10.2. backup
With backup: true, if the file changes, Ansible keeps the previous one next to it with a date suffix (for example, nginx.conf.12345.2026-11-26@10:15:02~) and returns its path in the result (backup_file). It's a useful safety net for critical files you weren't managing before (like the ones you're going to take over in this lesson), but:
- The copies pile up: one for every change. Review them and delete them from time to time.
- The copy stays in the same directory. Don't use it in directories whose whole content is read (
conf.d/*.confisn't affected because the copy doesn't end in.conf, but a directory served by the web server would publish the copies). - It's no substitute for git: the source of truth is the repository.
- Practice: a literal migration to templates
As in Module 4, first migrate without changing anything and check for changed=0; then improve. Add ansible_managed to ansible.cfg (section 9) and create the directories:
11.1. The nginx site
roles/nginx/templates/site.conf.j2:
# {{ ansible_managed }}
server {
listen {{ nginx_port }} default_server;
listen [::]:{{ nginx_port }} default_server;
server_name {{ nginx_server_name }};
root {{ nginx_root }};
index index.html;
location / {
try_files $uri $uri/ =404;
}
}In roles/nginx/tasks/site.yml, the task now looks like this:
- name: Configure the site in nginx
ansible.builtin.template:
src: site.conf.j2
dest: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
owner: root
group: root
mode: "0644"
notify: Reload nginx11.2. The PostgreSQL parameters
roles/postgresql/templates/parameters.conf.j2:
# {{ ansible_managed }}
listen_addresses = '{{ postgresql_listen_addresses }}'
port = {{ postgresql_port }}
max_connections = {{ postgresql_max_connections }}
shared_buffers = {{ postgresql_shared_buffers }}The first task of roles/postgresql/tasks/configure.yml:
- name: Configure the PostgreSQL parameters
ansible.builtin.template:
src: parameters.conf.j2
dest: "{{ postgresql_config_dir }}/conf.d/{{ postgresql_conf_name }}.conf"
owner: postgres
group: postgres
mode: "0644"
notify: Restart PostgreSQL11.3. The store website
roles/aurora_app/templates/index.html.j2:
{# Aurora Store home page. Uses inventory_hostname and aurora_app_domain. -#}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Aurora Store - Specialty Coffee</title>
</head>
<body>
<h1>Aurora Store</h1>
<p>Specialty coffee, roasted every Monday and shipped within 24 hours.</p>
<p><small>Served by {{ inventory_hostname }} - {{ aurora_app_domain }}</small></p>
</body>
</html>The Jinja comment documents the template without appearing on the page, and the dash in -#} prevents it from leaving an empty line at the beginning (section 8). In HTML you don't add ansible_managed: it would change the content of the page.
roles/aurora_app/templates/db.conf.j2:
# {{ ansible_managed }}
AURORA_DB_HOST={{ aurora_app_db_host }}
AURORA_DB_PORT={{ aurora_app_db_port }}
AURORA_DB_NAME={{ aurora_app_db_name }}
AURORA_DB_USER={{ aurora_app_db_user }}
AURORA_DB_DSN={{ aurora_app_db_dsn }}In roles/aurora_app/tasks/main.yml, replace the two corresponding tasks:
- name: Publish the store home page
ansible.builtin.template:
src: index.html.j2
dest: "{{ aurora_app_web_root }}/index.html"
owner: root
group: root
mode: "0644"- name: Publish the database connection details
ansible.builtin.template:
src: db.conf.j2
dest: "{{ aurora_app_config_dir }}/db.conf"
owner: root
group: root
mode: "0644"The "Publish the store static pages" task stays with copy: its content comes entirely from a variable, so there's nothing to fill in.
11.4. Checking the migration
PLAY RECAP *********************************************************************
db1 : ok=... changed=0 unreachable=0 failed=0 ...
web1 : ok=... changed=0 unreachable=0 failed=0 ...
web2 : ok=... changed=0 unreachable=0 failed=0 ...changed=0: the templates generate exactly the same files. If any task comes out changed, --diff will show you the difference; the most common cause is one blank line too many or too few, or an ansible_managed text that differs from what was there. Save this step:
git add ansible.cfg roles/
git commit -m "Role configuration in Jinja2 templates (literal migration)"
- Practice:
nginx.conf and a site with optional load balancing
nginx.conf and a site with optional load balancing12.1. nginx.conf with validate
Since Lesson 2.2, the inventory has defined nginx_worker_connections: 1024, but no role used it: the main file, /etc/nginx/nginx.conf, was the one installed by the package. Now that you have templates, the role can manage it. Add the parameter to roles/nginx/defaults/main.yml (with Ubuntu's value as the default):
# Simultaneous connections per nginx process (worker_connections directive).
nginx_worker_connections: 768And two constants to roles/nginx/vars/main.yml:
Create roles/nginx/templates/nginx.conf.j2, a simplified version of Ubuntu's file:
# {{ ansible_managed }}
user {{ nginx_user }};
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections {{ nginx_worker_connections }};
}
http {
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
gzip on;
include {{ nginx_conf_d_dir }}/*.conf;
include {{ nginx_sites_enabled_dir }}/*;
}All the include directives use absolute paths, as validate requires. Add the task at the beginning of roles/nginx/tasks/configure.yml:
- name: Publish the main nginx configuration
ansible.builtin.template:
src: nginx.conf.j2
dest: "{{ nginx_conf_file }}"
owner: root
group: root
mode: "0644"
validate: nginx -t -c %s
backup: true
notify: Reload nginxbackup: true because this is the first time Ansible takes over this file: if something doesn't convince you, you'll have Ubuntu's original right next to it. Later, in Lesson 9.2, you'll review this file from a security point of view (for example, hiding the version with server_tokens off).
12.2. The site, ready for load balancing
In Lesson 5.7 you'll add a load balancer to Aurora: another nginx server that doesn't serve files, but instead distributes requests between web1 and web2. Instead of writing a new role, the nginx role will learn to generate that kind of site with two more parameters. Add them to roles/nginx/defaults/main.yml:
# Load balancing (optional). If nginx_upstream_servers has elements, the site
# doesn't serve files: it forwards requests to those servers.
# Dictionary {address: weight}, for example {"192.168.56.11": 2, "192.168.56.12": 1}.
nginx_upstream_servers: {}
# Port the nginx_upstream_servers listen on.
nginx_upstream_port: 80And replace roles/nginx/templates/site.conf.j2 with the full version:
# {{ ansible_managed }}
{% if nginx_upstream_servers %}
upstream {{ nginx_site_name }}_backend {
{% for address, weight in nginx_upstream_servers.items() %}
server {{ address }}:{{ nginx_upstream_port }} weight={{ weight }};
{% endfor %}
}
{% endif %}
server {
listen {{ nginx_port }} default_server;
listen [::]:{{ nginx_port }} default_server;
server_name {{ nginx_server_name }};
{% if nginx_upstream_servers %}
location / {
proxy_pass http://{{ nginx_site_name }}_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
{% else %}
root {{ nginx_root }};
index index.html;
location / {
try_files $uri $uri/ =404;
}
{% endif %}
}Read it piece by piece:
- The
upstreamblock: it's only generated ifnginx_upstream_servershas elements. The loop iterates over the dictionary with.items()and writes oneserverline for each address, with its weight. The name of the group is derived from the site name (aurora_backend). - Inside
server: if there are backend servers, the onlylocationforwards everything withproxy_passand passes the usual headers (the requested name, the client's real IP and the protocol). If not, the site serves files fromnginx_root, exactly as before. - Whitespace: all the
{% %}tags are in column 0, and the blank line that separatesupstreamfromserveris inside theif, so it doesn't appear when there's no load balancing.
On the web servers, nginx_upstream_servers is empty: the generated file must be identical to the current one. And to see what a load balancer would look like without touching anything, use --check --diff with extra variables in JSON (the way to pass a dictionary with -e, Lesson 3.5):
ansible-playbook webservers.yml --check --diff --limit web1 \
-e '{"nginx_upstream_servers": {"192.168.56.11": 2, "192.168.56.12": 1}}'--- before: /etc/nginx/sites-available/aurora
+++ after: /home/student/aurora-infra/roles/nginx/templates/site.conf.j2
@@ -1,13 +1,26 @@
# Managed by Ansible (aurora-infra). Do not edit by hand.
+upstream aurora_backend {
+ server 192.168.56.11:80 weight=2;
+ server 192.168.56.12:80 weight=1;
+}
+
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name aurora-store.example www.aurora-store.example;
- root /var/www/aurora;
- index index.html;
-
location / {
- try_files $uri $uri/ =404;
+ proxy_pass http://aurora_backend;
+ proxy_set_header Host $host;
...It's only a simulation: don't apply that change to a web server (it would forward requests to itself).
12.3. Updating the argument specification
Three new variables in defaults/main.yml mean three new entries in roles/nginx/meta/argument_specs.yml (Lesson 4.6). Add them under options:
nginx_worker_connections:
type: int
default: 768
description: Simultaneous connections per process (worker_connections in nginx.conf).
nginx_upstream_servers:
type: dict
default: {}
description:
- Servers to forward requests to, as a dictionary {address = weight}.
- If it's empty, the site serves static files from nginx_root.
nginx_upstream_port:
type: int
default: 80
description: Port of the nginx_upstream_servers.Finally, in inventory/group_vars/webservers.yml, nginx_worker_connections: 1024 at last takes effect. Don't change anything: the value has been there since Module 2.
- Practice: a complete
pg_hba.conf
pg_hba.confUntil now, the postgresql role added rules to pg_hba.conf with the community.postgresql.postgresql_pg_hba module, but the rest of the file was the package's. That carries a risk: if someone adds a permissive rule by hand, Ansible doesn't see it or remove it. With a template, the role manages the complete file: what isn't in the template isn't on the server.
roles/postgresql/templates/pg_hba.conf.j2:
# {{ ansible_managed }}
# TYPE DATABASE USER ADDRESS METHOD
# Local connections: Unix socket (peer) and localhost.
# The first rule is essential: Ansible connects as postgres through the socket.
local all postgres peer
local all all peer
host all all 127.0.0.1/32 scram-sha-256
host all all ::1/128 scram-sha-256
local replication all peer
host replication all 127.0.0.1/32 scram-sha-256
host replication all ::1/128 scram-sha-256
# Authorized remote clients ({{ postgresql_hba_clients | length }}).
{% for client in postgresql_hba_clients %}
host {{ postgresql_hba_database }} {{ postgresql_hba_user }} {{ client }}/32 {{ postgresql_hba_method }}
{% else %}
# None.
{% endfor %}- The local rules are the ones Ubuntu ships by default. They're the foundation of everything: if
local all postgres peerwere missing, the role's tasks (which usebecome_user: postgres) would no longer be able to connect. - The loop generates one rule per client, with the same parameters the module used to receive; the
elserecords that there are no clients. {{ postgresql_hba_clients | length }}documents in the file itself how many clients there are.
Replace roles/postgresql/tasks/access.yml with:
---
- name: Configure access control (pg_hba.conf)
ansible.builtin.template:
src: pg_hba.conf.j2
dest: "{{ postgresql_config_dir }}/pg_hba.conf"
owner: postgres
group: postgres
mode: "0640"
backup: true
notify: Reload PostgreSQLThe task's loop is gone: it's now inside the template. The 0640 permissions are the ones Ubuntu gives this file.
Before applying it, look at what's going to happen:
The diff shows that the long comments of the original file disappear and that the rules end up in the template's order. It's an expected change: from now on, the file belongs to Ansible. Apply it and check the rules PostgreSQL has loaded:
ansible-playbook dbservers.yml
ansible db1 -b --become-user postgres -m ansible.builtin.command \
-a "psql -c 'SELECT line_number, type, database, user_name, address, auth_method, error FROM pg_hba_file_rules'" line_number | type | database | user_name | address | auth_method | error
-------------+-------+-------------+------------+---------------+-------------+-------
6 | local | {all} | {postgres} | | peer |
7 | local | {all} | {all} | | peer |
...
15 | host | {aurora} | {aurora} | 192.168.56.11 | scram-sha-256 |
16 | host | {aurora} | {aurora} | 192.168.56.12 | scram-sha-256 |The empty error column confirms that all the rules are valid. The role no longer uses the postgresql_pg_hba module; it still needs the community.postgresql collection for users and databases. Update the corresponding note in roles/postgresql/README.md if you mentioned it.
- Verifying and saving the work
Apply the whole infrastructure:
On this first run you expect exactly these changes:
| Host | changed task |
Handlers |
|---|---|---|
web1, web2 |
Publish the main nginx configuration (worker_connections 768 → 1024 and a simplified file) |
Validate the nginx configuration, Apply the nginx reload |
db1 |
None (you already applied pg_hba.conf in section 13) |
None |
A second run should give changed=0 on all of them. Check that the website still responds and that the backup is in place:
curl -s http://192.168.56.11/ | grep Served
ansible webservers -b -m ansible.builtin.shell -a "ls /etc/nginx/nginx.conf*"Save the work:
git add ansible.cfg roles/
git commit -m "nginx.conf and pg_hba.conf managed with templates; nginx site with optional load balancing"Common Mistakes and Tips
- "Could not find or access 'site.conf.j2'": the template isn't in the role's
templates/directory (or the name doesn't match). The error message includes the "Searched in" list from Lesson 4.3. template error while templating string: unexpected '}': there's an unclosed{{or{%, or the configuration file contains a sequence that Jinja interprets ({#in some formats). Use{% raw %}for the literal fragment.- One blank line too many or too few after migrating: that's whitespace control. Write the
{% %}tags in column 0 and compare with--check --diffbefore applying. AnsibleUndefinedVariableinside the template: a variable doesn't exist for that host. Remember that the role should only read its own variables (prefix) and that thedefaultinargument_specsdoesn't define anything.- A file that changes on every run: the template uses something that varies (the date,
template_run_date, a non-deterministic order). Dictionaries keep the order in which they're defined, but if you build lists from sets, sort them (Lesson 5.3). validatewith a fragment:nginx -t -c %son aserverblock always fails. For fragments, validate in the handler.- Tip: when you take over a file you weren't managing before, use
--check --difffirst, apply withbackup: trueand verify the service. It's the safe way to go from "what's there" to "what the code says".
Exercises
Exercise 1: The common role templates
The common role still publishes /etc/motd and the local facts with copy and content:. Move them to the templates roles/common/templates/motd.j2 and roles/common/templates/facts.fact.j2 without any file changing on the servers (changed=0).
Exercise 2: A warning in the motd depending on the environment
Modify motd.j2 so that, only when common_env is production, it adds the line WARNING: production server. before the incidents line. Check with --check --diff that nothing changes in the lab (aurora_env: lab), and that with -e aurora_env=production the line would appear.
Exercise 3: Reading a template
Without running it, write the result of site.conf.j2 for nginx_upstream_servers: {"10.0.0.5": 3}, nginx_upstream_port: 8080, nginx_site_name: blog, nginx_port: 80 and nginx_server_name: blog.example.
Solutions
Exercise 1. roles/common/templates/motd.j2 (without ansible_managed, because the current motd doesn't have it and every user would see it when logging in):
==========================================================
{{ common_organization }} - {{ inventory_hostname }} ({{ common_env }})
Access restricted to authorized personnel.
Incidents: {{ common_contact }}
==========================================================roles/common/templates/facts.fact.j2:
[general]
env={{ common_env }}
domain={{ common_domain }}
groups={{ group_names | join(',') }}
managed_by={{ common_managed_by }}The tasks in roles/common/tasks/main.yml:
- name: Configure the welcome message (motd)
ansible.builtin.template:
src: motd.j2
dest: /etc/motd
owner: root
group: root
mode: "0644"- name: Publish the local facts
ansible.builtin.template:
src: facts.fact.j2
dest: "{{ common_facts_dir }}/{{ common_facts_name }}.fact"
owner: root
group: root
mode: "0644"
register: common_local_factsCreate the directory first with mkdir roles/common/templates. ansible-playbook common.yml should finish with changed=0. The rest of the course assumes this solution has been applied.
Exercise 2. In motd.j2, between the restricted access line and the incidents line:
Access restricted to authorized personnel.
{% if common_env == 'production' %}
WARNING: production server.
{% endif %}
Incidents: {{ common_contact }}With the tags in column 0, in lab the result is identical to the previous one. ansible-playbook common.yml --check --diff -e aurora_env=production would show the new line (and also the change to env= in the facts, because common_env comes from aurora_env). Since -e has the highest precedence, it's a good way to preview without changing the inventory.
Exercise 3.
# Managed by Ansible (aurora-infra). Do not edit by hand.
upstream blog_backend {
server 10.0.0.5:8080 weight=3;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name blog.example;
location / {
proxy_pass http://blog_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Conclusion
All the configuration of the Aurora roles now lives in Jinja2 templates inside the templates/ directories: nginx.conf.j2 and site.conf.j2 in nginx, parameters.conf.j2 and pg_hba.conf.j2 in postgresql, index.html.j2 and db.conf.j2 in aurora_app, and motd.j2 and facts.fact.j2 in common. You know the three kinds of Jinja2 markup ({{ }}, {% %} and {# #}), conditionals, loops with the loop variable and the else of for, whitespace control with trim_blocks, lstrip_blocks and the dash, the common ansible_managed header configured in ansible.cfg, and the validate parameter (for complete files like nginx.conf) and backup parameter (for safely taking over a file). On top of that, Aurora now manages nginx.conf with the worker_connections from the inventory, a complete pg_hba.conf and an nginx site capable of acting as a load balancer. In the templates you've used a few filters (join, length, default) almost without noticing. In the next lesson, Filters and Lookups, you'll study them in depth: how to transform lists and dictionaries, combine data from several hosts, generate passwords and read information from the control node, and you'll discover how to automatically build the list of servers the load balancer will need.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
