A running service does not reread a new config by itself. It has to be restarted — but only when the config changed.
service with state: started leaves a running nginx alone: change the port in the config, and the file is updated while nginx keeps listening on the old one. state: restarted restarts it on every run, and connections break again.
That is what a handler is for — a task in a separate handlers section of the play. An ordinary task calls it with a notify line naming the handler:
A handler fires only if the task that called it answered changed, and only once — at the end of the play, after all the tasks. In the output it is a RUNNING HANDLER line (in the Wiki).
Restart nginx with a handler
Your colleague changed the site port in ~/ansible-lab/site.yml to 8081, while nginx still listens on 8080. Add a handler that restarts nginx to the playbook, call it from the config task, and only then run the playbook. The site has to answer on http://127.0.0.1:8081/, and the next run has to change nothing.
Goals · 0 of 3
- Restart nginx with a handler after the config edit not done yet
- Move the site to port 8081 not done yet
- Make the next run change nothing not done yet
Since a handler waits for the end of the play, notify on several tasks — say, the config and the certificate file — still gives one handler run: two edits, one restart. And when the task answers ok, the handler stays silent, and a run without edits restarts nothing.
A handler sees only the changes of its own run. If a run without notify already applied the edit, the next run finds the file in place — the task answers ok, and the handler does not fire.
A playbook with an nginx restart handler was run, the config changed, and nginx restarted. What will the next run do if neither the playbook nor the machine was touched?
-
The config on the machine already matches the description, so the task answers
ok.ansible-playbook site.yml --checkshowschanged=0. -
A written-down handler waits for a
notifyfrom a task that changed something. With no change there is noRUNNING HANDLERline in the output. -
A handler can be called in every run any number of times. Here nobody calls it: the task answers
ok.
A handler fires only on notify from a task that answered changed. The config on the machine is already as in the playbook, so the task answers ok, nginx is left alone, and PLAY RECAP says changed=0.