Day 56 of #90DaysOfDevOps
Ansible ad hoc commands are one-liners designed to achieve a very specific task they are like quick snippets and your compact Swiss army knife when you want to do a quick task across multiple machines.
To put simply, Ansible ad hoc commands are one-liner Linux shell commands and playbooks are like a shell script, a collective of many commands with logic.
Ansible ad hoc commands come in handy when you want to perform a quick task.
Task - 1
Write an ansible ad hoc ping command to ping 2 servers from the inventory file.
Write an ansible ad hoc command to check uptime.
First, create 3 servers and configure one of them as master(install Ansible). You can refer to this blog.
Second, create an inventory file or modify the default "hosts" file and enter the servers as well as required vars. Here I will create a new file and proceed.
I created a folder and then a file called my-servers. You can also save files with .ini extension.
Ansible ad_hoc commands Syntax
To run an ad hoc command, the command must be framed or have the following syntax.
ansible <host-pattern> [options]
For example. the command should be written as follows.
ansible appserverhostgroup -m <modulename> -a <arguments to the module>
A single ansible ad hoc command can have multiple options. -m
and -a
are one amongst them and widely used.
To ping servers, write command ansible -i /home/ubuntu/inventory/my-servers servers -m ping
and enter.
Here, -i
is for INVENTORY.
To check uptime, we need to give argument [-a] uptime.
Ansible provides two major modules to run the command over the host group or on the remote server.
Which one to pick is not a big confusion if you know what are they and their capabilities
FAQ: Ansible command vs shell module
Both ansible shell and command modules can be used to run SHELL commands on the nodes. but one difference is that command module does not support piping the output to another command, In other words, it will support the only command whereas shell module support complicated pipes and every shell command you use day to day
The UNIX Command | Supported in command module | Supported in Shell module |
cat /etc/passwd | YES | YES |
cat /etc/passwd|grep "^saravak" | NO ( Since it has Pipe) | YES |
Here are the commands you can use to get the uptime. All three commands would yield the same results.
ansible multi -m command -a uptime
ansible multi -m shell -a uptime
ansible multi -a uptime
As you could have already figured out -m is the module and -a should contain the command it should run which goes as an argument to command and shell.
Thank you!