0 / 13 lessons — 0%
Lesson 07 / 13
Handlers, idempotency & tags
Idempotency is Ansible's core promise: running the same playbook twice produces the same end state, and the second run reports nothing changed. The apt module checks if nginx is already installed before installing it; copy checks if the file content already matches before copying. You get this for free by using proper modules instead of raw shell commands.
Every task compares actual vs. desired before touching anything — matching state means no action, no "changed" report.
A handler is a task that only runs when explicitly notified by another task — the classic use is "only restart nginx if its config actually changed," instead of restarting it (and dropping active connections) on every single run.
tasks: - name: Deploy nginx config template: src: nginx.conf.j2 dest: /etc/nginx/sites-available/app.conf notify: Restart nginx handlers: - name: Restart nginx service: name: nginx state: restarted
Tags let you run only part of a long playbook — handy when you don't want to redo every step just to fix one thing.
tasks: - name: Install nginx apt: { name: nginx, state: present } tags: [install] - name: Deploy config template: { src: nginx.conf.j2, dest: /etc/nginx/sites-available/app.conf } tags: [config]
ansible-playbook site.yml --tags config
Try it yourselfAdd a handler to a playbook that changes a config file, run the playbook twice in a row. First run: "changed", handler fires. Second run: nothing changed, handler never fires. That's idempotency and handlers working together exactly as intended.