how to run local command via ansible-playbook
I like delegate_to. Here's an example that, on localhost, runs getent hosts for each host:
---
- hosts: all
connection: ssh
gather_facts: true
tasks:
- name: Lookup ansible_hostname in getent database
command: getent hosts {{ ansible_hostname }}
delegate_to: localhost
register: result
- name: Show results
debug:
var: result.stdout
delegate_to: localhost
You could access the hostname by using the following play, as the inventory information are available as hostvars.
- hosts: 127.0.0.1
connection: local
gather_facts: no
tasks:
- debug: var=hostvars
- name: node create
command: "knife node create {{ hostvars[item]['hostname'] }}"
with_items:
- "{{ groups['qa-hosts'] }}"
Another alternative is local_action.
In the case of both delegate_to
and local_action
, be aware that if become = yes
then Ansible will of course implicitly try to invoke the action using sudo
, and then will probably fail because the password for local sudo
will be different to any password you entered for remote sudo
.