Ansible Handlers
In this lesson, you will learn about Ansible handlers, their importance in playbook design, and how to effectively use them to manage service states or perform tasks based on the results of other tasks. Handlers are special tasks in Ansible that run only when notified by another task. This mechanism is particularly useful for optimizing your automation scripts by ensuring certain actions, like restarting a service, are only performed when necessary.
Understanding Ansible Handlers
Handlers are triggered by other tasks in your Ansible playbook that might make changes requiring a service restart or another follow-up action. For instance, if you're deploying a new version of a web application and need to restart the web server to apply the changes, you'd use a handler for the restart action. The beauty of handlers is that they run at the end of your playbook's execution and only if they've been 'notified' by another task, ensuring that a service is not unnecessarily restarted multiple times, which could cause service downtime or other issues.
How to Define and Use Handlers
To define a handler, you'll usually place it under the handlers section in your Ansible playbook or inside role/handlers/main.yml.
Let's create a handler that will restart the Nginx service. Nano the following file to create the handler YAML file:
nano roles/webserver/handlers/handlers.yml
Next, create the handler like so:
Save and close the file.
__
If you are defining a handler outside of the context of a role, you can define the handler in your playbook below the tasks like so:
This handler, named restart nginx, uses the service module to restart the Nginx service. To trigger…
No comments yet. Add the first comment to start the discussion.