Ansible Ad Hoc Commands


In this video we will take a look at how we can use the ansible command (as opposed to the ansible-playbook command which we will use predominantly throughout the rest of this series) to run commands on a one time (or ad-hoc) basis.

Ad-hoc commands are commands that you want to try, but don't necessarily want to create a full playbook for.

In the video, we use the example of a ping command.

ansible all -m ping

This is going to run the ping module against all the hosts in our Hosts file. In the example there is only one entry in our Hosts file, but if ten were in there, then all ten would be pinged.

As this is the first time we are trying to run a command against the machine - even though the target machine is the machine running the command - we will be asked to verify the authenticity of the host we are connecting too. This is a typical SSH prompt, and highlights the fact that Ansible is using SSH to complete this command.

As the fail message isn't particularly helpful - we hit an unknown error - we can do as Ansible suggests and re-run the command with the -vvvv argument, which will enable very, very, very verbose debugging output.

ansible all -m ping -vvvv

The downside to this is that the output of -vvvv is so overwhelming that it almost goes to the opposite end of the spectrum, whilst being almost equally unhelpful to a beginner.

When we re-run the command with -vvvv, effectively Ansible is telling us we can't connect without a password as we don't have an SSH key pair setup. We could set that up at this stage, but there's a quicker way round this for now, by re-running the command but this time telling Ansible we will provide the required passwords:

ansible all -m ping -k

There are a lot of arguments you can provide to the Ansible command, and I personally find this manual (man) page simpler to use than the Ansible documentation for this.

The most important three for now are:

-k Prompts for the SSH password instead of assuming key-based authentication with ssh-agent.

-K Prompts for the password to use with -s, if any

-s Run the command as the user given by -u and sudo to root.

So when we run ansible all -m ping -k we will be asked for the SSH password, and when providing a valid SSH password, we will immediately get a successful response from Ansible.

There are many commands you can run on an ad-hoc basis using Ansible. I don't tend to use this command very frequently, as the real power for me at least, lies in the playbooks. But it's great to know of this functionality and capability all the same.

To find more commands, I cover a few in the video, but the Ansible manual page for the ad-hoc commands is pretty useful for more examples.

Code For This Course

Get the code for this course.

Episodes