Going further / Lesson 1 of 2
Variables, Templates and Handlers
Make playbooks flexible with variables and Jinja2 templates, and restart services only when something changed.
8 min Intermediate 7 steps
IN THIS LESSON
Step 1 of 7
STEP 1 / 7
Variables hold the values
Instead of hard-coding a port or a path, store it in a variable and refer to it by name with double braces. Change the value once and every use follows.
vars:
http_port: 8080
# used in a task as:
# {{ http_port }}← → step · R replay · Space play/pause
YOU'LL LEARN
- How variables are defined and used
- How Jinja2 templates generate config files
- How Ansible decides a task changed something
- How handlers run only when notified
- Variables hold the values. Instead of hard-coding a port or a path, store it in a variable and refer to it by name with double braces. Change the value once and every use follows.
- Templates build config files. A template is a file with placeholders, written in the Jinja2 language. Ansible fills the placeholders with variables, so one template can produce a slightly different file for every host.
- Render and deliver. The template module renders the file on the control node and copies the result to the managed node.
- Changed or not?. If the rendered file is identical to the one already on the node, the task reports ok and nothing happens. If it differs, the file is replaced and the task reports changed.
- Handlers react to changes. A new config file is useless until nginx reloads it, but you do not want to restart nginx on every run. A task can notify a handler, which is a task that runs only when it has been notified by something that changed.
- Handlers run once, at the end. Handlers wait until the end of the play and run once, even if several tasks notified them. If nothing changed, they do not run at all, so unchanged servers are never restarted.
- Recap. Variables, templates and handlers turn a fixed script into a flexible, change-aware automation.