- In this video,
we are going to explore the use of handlers.
So what is a handler?
A handler is a task that is only executed
when it is triggered by a task
that has changed something.
Handlers are executed after all tasks in a play.
So that's important to realize,
and you need to organize the contents
of your playbook accordingly.
And if any task fails after the task
that has called the handler,
the handler is not executed at all.
If you don't like that,
you need to use force handlers to change that behavior.
Let's go check out an example.
So let's have a look at an example.
The example is in handlers.yml.
So what are we doing?
We are running the playbook on the host rocky.
We install httpd,
then we copy over an index html file.
That's a file that should exist in tmp index html.
And this is the important part about the handler,
we use notify restart web.
Restart web actually needs to correspond
to the name of the handler.
And that is the case as you can see right here.
So name it restart web.
And then that's the interesting thing,
I included the task that is going to fail.
We will have a failure on purpose.
That's exactly what I want to demonstrate.
So I want to demonstrate
that the handler is not going to run,
if any of the tasks that is triggered
after the handler is going to fail.
So let's run it and figure out what's going to happen.
Ansible playbook and handlers.yml.
So here we can see copy index html has changed something.
So it should trigger the handle normally,
but after this handle triggering task,
another task is failing.
And the default behavior
in Ansible happens to be if execution
of a specific task, on a specific host, is failing.
Then further play execution on that host is aborted.
And for that reason, we don't see the handler.
Now, if you want to change that behavior
that is pretty easy.
You need to get back in the handler's code
and you need to use force handlers:yes
or true or whatever.
It's a boolean,
so you can go whatever way you want.
Ansible is pretty flexible,
regarding the way how you write your boolean.
So let's run it again.
And here we can see that...
Oh boy, nothing is happening.
Why isn't anything happening?
I'll take a second to think about it.
Did you think about it?
Have a look at the task copy index html
which hasn't changed anything.
And this is the mere essence of using handlers.
Handlers are going to be operational
if something has changed.
So the index html already existed.
And that means that I need
to use an ad hoc command Ansible all minus m file
minus a name is /var/www/html/index.html
and state is absent.
And then I'm going to run it again
and then we will see what is going to happen.
So now we can see that yeah,
index html is changing something.
Copy nothing is still failing,
but the handler has restarted web.
And that is what I wanted you to see here.
Force handlers allows you to force the handlers
to be started,
even if any subsequent tasks are failing.
And that's all.