Run command on the Ansible host
I'd like to share that Ansible can be run on localhost via shell:
ansible all -i "localhost," -c local -m shell -a 'echo hello world'
This could be helpful for simple tasks or for some hands-on learning of Ansible.
The example of code is taken from this good article:
Running ansible playbook in localhost
You can use delegate_to
to run commands on your Ansible host (admin host), from where you are running your Ansible play. For example:
Delete a file if it already exists on Ansible host:
- name: Remove file if already exists
file:
path: /tmp/logfile.log
state: absent
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
Create a new file on Ansible host :
- name: Create log file
file:
path: /tmp/logfile.log
state: touch
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
I've found a couple other ways you can write these which are a bit more readable IMHO.
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.
If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1
and connection:local
in the play, for example:
- name: a play that runs entirely on the ansible host
hosts: 127.0.0.1
connection: local
tasks:
- name: check out a git repository
git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Local Playbooks in the Ansible documentation for more details.
If you just want to run a single task on your Ansible host, you can use local_action
to specify that a task should be run locally. For example:
- name: an example playbook
hosts: webservers
tasks:
- ...
- name: check out a git repository
local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See "Controlling where tasks run: delegation and local actions" in the Ansible documentation for more details.
You can avoid having to type connection: local
in your play by adding this to your inventory:
localhost ansible_connection=local
(Here you'd use "localhost
" instead of "127.0.0.1
" to refer to the play).
In newer versions of Ansible, you no longer need to add the above line to your inventory, Ansible assumes it's already there.