Execute command on the Ansible host — Ansible localhost

How to execute Ansible command(s) or task(s) on localhost using the connection plugin local and the right ansible internals variables.

Ansible Pilot
4 min readMar 9, 2022


How to Execute command on the Ansible host?

When Ansible becomes part of your daily workflow it is natural you would like to automate also task in your local machine.

I’m going to show you a live demo with some simple Ansible code.

I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

Execute command on the Ansible host options

  • connection plugin
  • delegate_to: localhost
  • local_action

There are three ways to execute modules and commands on the Ansible Controller host.

The first and my favorite is using the connection plugin `local` and applying it to the Ansible Play level of your Playbook. The tricky was is to adjust some ansible variables about the python interpreter. I consider it the best way nowadays.

The second way is using the `delegate_to` at the Task level. This has the advantage to delegate only one task to localhost but still needs only the implicit localhost scheme.

The third way is using the `local_action` statement. I personally don’t like it but it’s one alternative as well at Task level, so same as the previous.



How to Execute command on the Ansible host using connection: local method.


- name: localhost demo
hosts: localhost
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
- name: print hostname
msg: "{{…



Ansible Pilot

I help creative Automation DevOps, Cloud Engineer, System Administrator, and IT Professional to succeed with Ansible Technology to automate more things everyday