So there may be occasions where you want to run a particular
task on a control machine instead of on the remote host itself.
In this case, Ansible provides us with the local_action clause
to support this requirement.
So let's say we want to install an app to a host that is just booted up.
However,
if we run our playbook too soon, we would get an error, as the server
has not completely booted. In this case, we could start our playbook by
including the wait_for, and this allows us to wait until SSH server is
ready to accept. With this playbook, we are referencing an inventory
host name in the task.
As a result,
it will evaluate the name of the remote host and not the local host,
so the scope of the variable is still the remote host, but the task
is executing locally. Most of the time, all the tasks are executed on
each host in the inventory.
However, what if you need to run one or two tasks on different hosts?
Well, this is known as task delegation.
This is a convenient way, as it allows you to run individual
tasks on different hosts without needing to start the new play
that addresses the host specifically.
So by default,
Ansible gathers facts and execute all tasks on the machines
that match the host line in your playbook. You can delegate
tasks to different machines or groups.
We can also delegate facts to specific machines or groups
or even run the entire playbook locally.
For example, let's say you want to update a group of web servers,
you might need to remove them from a load balancer pool,
but just for a temporary time. You cannot perform this task on the web servers
themselves, so what we would do is we'd delegate this task to the local host
and you keep all the tasks within the same play.
So some tasks that cannot be delegated are always executed on the controller.
These tasks include add_host and debug, all of which cannot be delegated.
So if you want to perform a task on one host concerning other hosts,
we have what's known as the delegate_to keyword in the task. So many facts
that are gathered by the delegate tasks are assigned by default to the
inventory_hostnames, which is the current host, and not to the host which
produced the facts, which would be the delegate host. To assign gathered
facts to the delegated host, instead of the current host, we set
delegate_facts to true.
So the delegation host must meet the same
requirements as the regular control host.
So here we're going to run a task from the managed host,
so you need to have the following.
Firstly, you need to have Python installed. Then you need to have SSH
access to the managed host, host resolution must be working, and the
delegated host must be in the inventory.