Is it possible to run commands on the Ansible host?
My scenario is that I want to take a checkout from a git server that is hosted internally (and isn't accessible outside the company firewall). Then I want to upload the checkout (tarballed) to the production server (hosted externally).
At the moment, I'm looking at running a script that does the checkout, tarballs it, and then runs the deployment script - but if I could integrate this into Ansible that would be preferable.
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
andconnection:local
in the play, for example: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:See Delegation in the Ansible documentation for more details.
Edit: You can avoid having to type
connection: local
in your play by adding this to your inventory:(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).
Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.
I've found a couple other ways you can write these which are a bit more readable IMHO.
OR
The default module is command module, hence
command
keyword is not required.If you need to issue any command with elevated privileges use
-b
at the end of the same command.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:
Create a new file on Ansible host :
Expanding on the answer by @gordon, here's an example of readable syntax and argument passing with shell/command module (these differ from the git module in that there are required but free-form arguments, as noted by @ander)
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