Ansible in a Minute · Ansible Core ·
Use delegate_to to run a task on another host
Short answer
Use delegate_to so a task runs on localhost (or another host) while the play still targets the current inventory host.
Subscribe for updates
Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.
By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.
Request
echo inventory_hostname delegated to localhost
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
- name: Echo inventory_hostname on the controller
hosts: all
gather_facts: false
tasks:
- name: Echo inventory_hostname
ansible.builtin.command:
cmd: echo "{{ inventory_hostname }}"
delegate_to: localhost
changed_when: falseHow it works
delegate_to changes where the task runs. inventory_hostname still names the current play host. Use this when the work must happen on the controller or on a load-balancer host, not on the target.
When to use it
- Updating a pool or inventory record on the controller
- Running a command that only exists on localhost
Requirements
- Ansible: >=2.14
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-09-15
Notes
debug cannot be delegated. Connection variables on the task refer to the delegated host. Prefer a host that exists in inventory. Pair with run_once when many hosts would write the same file in parallel.
Reference
- Delegating tasks (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.