Module 2 · Project 02 · Automated Server Configuration with Ansible · Lesson 8 of 48
Variables, templates and handlers
Make the playbook reusable with variables and Jinja2 templates, and restart services only when their config changes.
In this lesson · about 25 minutes
- Use variables in tasks and in group_vars files
- Render configuration files from Jinja2 templates
- Use notify and handlers to restart a service only when needed
Variables
Hard-coded values make a playbook work in one place only. Variables pull them out:
# group_vars/web.yml (applies to every host in the web group)
server_name: noviq.example
app_port: 3000
worker_processes: auto
Use them anywhere with double curly braces: "{{ server_name }}". In YAML, a value that starts with {{ must be in quotes.
Templates
The template module reads a Jinja2 file from your repo, fills in the variables, and writes the result to the server:
# templates/site.conf.j2
server {
listen 80;
server_name {{ server_name }};
location / {
proxy_pass http://127.0.0.1:{{ app_port }};
}
}
Handlers: restart only when something changed
After changing nginx's config, nginx must reload it. But restarting on every run would cause needless blips. A handler is a task that runs only when another task notifies it, and only if that task reported changed. However many tasks notify it, a handler runs once, at the end of the play.
tasks:
- name: Deploy the site config
ansible.builtin.template:
src: templates/site.conf.j2
dest: /etc/nginx/conf.d/site.conf
validate: nginx -t -c %s # refuse a broken config
notify: Restart nginx
handlers:
- name: Restart nginx
ansible.builtin.service: { name: nginx, state: restarted }
The same pattern hardens SSH safely: a lineinfile task on sshd_config notifies a "Restart sshd" handler.
Try it · watch it run
Handlers: restart only when needed
Choose which templates changed, then step through the play. Watch the notify list, and count the restarts.
Task results
Notify list (handlers waiting)
(empty)
Whiteboard · watch and try
How a template becomes a file
Press Play to follow one variable from group_vars to the server.
Tip: press Pause, then use the pen to work along on the board. Space plays and pauses; Ctrl+Z undoes your last mark.
Check your understanding0 of 3 correct
Key terms
Say the meaning to yourself, then tap a card to check.
Quiz score: 0 of 3
Written by Noviq Academy in its own words. The labs are simulations: no real servers are touched. When you build the projects yourself, use a practice virtual machine or a free-tier cloud account you control, watch your cloud spending, and never run cleanup or delete commands on a machine you care about. Tool names belong to their owners; versions and output are shown for learning and may differ slightly from yours. Read-aloud and the whiteboard voice use your device's built-in voices.