Delegation in Ansible

From bib. source

Some tasks […] require Ansible to run the task on the host machine (running the playbook) or another host besides the one(s) being managed by the playbook. Ansible allows any task to be delegated to a particular host using delegate_to

That is, the delegate_to field or key in an Ansible YAML playbook file is used to override the hostname / FQDN / public IP address a module or task in the playbook is run at or on, for that given task only (Geerling 2023, 114). That is, it allows for a temporary departure from the hostnames / FQDNs / public IP addresses for which a play occurs for given tasks (Ibid). Here is an example of a task using delegate_to in a hypothetically larger playbook–in this case to delegate to localhost or a loopback address (Ibid):

- name: Remove server from load-balancer.
  command: remove-from-lb {{ inventory_hostname }}
  delegate_to: 127.0.0.1

In the case of delegation to localhost or a loopback address, there is actually an even better shorthand field available, local_action, wherein its value is the module name and then the value for that module (Geerling 2023, 114-115):

- name: Remove server from load-balancer
  local_action: command remove-from-lb {{ inventory_hostname }}

IP_address Internet_Protocol_address Internet_Protocol fully_qualified_domain_name fully_qualified_domain_names loopback_address loopback_addresses configuration_management


bibliography

  • “Ansible Playbooks - Beyond the Basics.” In Ansible for DevOps: Server and Configuration Management for Humans, 2nd ed., 84–122. Leanpub, 2023.