In our previous article, we have discussed what is ansible inventory and configuration file which lays the foundation to learn Ansible. In this article, we are going to discuss ansible ad hoc commands with some examples.
Ansible Ad hoc commands are great when you want to run any quick tasks and tasks that are not repeated frequently. Typically these ad hoc commands will be one-liner commands that you can either run directly from the terminal or from the shell script.
Before getting to know how to work with ad hoc commands, you should get to know what idempotent is. Ansible is idempotent in nature, meaning irrespective of how many times you run the same task if an object state is already changed, then ansible will not try to make the same changes again to that object.
Ad hoc commands are submitted through
/usr/bin/ansible program. You can run the following command to get the list of supported options for the ansible command.
$ ansible --help
If you have no ansible lab to practice, then you can take a look at our guide on how to set up ansible manually as well as using Vagrant and Virtualbox.
- Install And Configure Ansible In Linux
- Automated Ansible Lab Setup With Vagrant And Virtualbox In Linux
Get to Know the Target
Before working with ad hoc commands or writing playbooks, you should have a clear understanding about the business requirement and the target environment you are going to work with.
The target environment can be anything like servers, network devices, containers, cloud solutions, etc.. that ansible supports. Here I am using two managed nodes that are running Ubuntu 20.04.
You can run the following command to check the list of hosts that will be used when you run ad hoc command or playbook.
#SYNTAX $ ansible --list-hosts
Group name can be default(all, ungrouped) or user-defined groups.
If you want to learn more about groups, refer the following link.
Get the list of hosts for all groups.
$ ansible all --list-hosts hosts (2): managed1.anslab.com managed2.anslab.com
Get a list of hosts for the user-defined group. Here my group name is ubuntu.
$ ansible ubuntu --list-hosts hosts (2): managed1.anslab.com managed2.anslab.com
The Inventory file holds the list of managed nodes. The inventory file location will be configured in the
ansible.cfg file. You can override the inventory file location using the
--inventory flag when running ad hoc commands.
I have two inventory files and the default file is named hosts. To use the file host2, I need to use the
-i flag and pass the file as the argument.
$ ansible all -i host2 --list-hosts hosts (1): managed2.anslab.com
Heads Up: If the inventory file is in a different location, you have to provide the absolute path. You can refer to the following link to know the order of precedence for the inventory file.
Ansible is a battery included tool meaning it has tons of modules shipped with it. Modules are programs written in Python that is used by ansible to run on the managed nodes to perform a task. Ansible follows plug and play approach meaning you can write your own module and run it through ansible.
Ansible supports lots of packages that were created by the open-source community and different product vendors. To get the list of all modules installed on your machine run the following command.
$ ansible-doc -l # LIST ALL MODULES AVAILABLE $ ansible-doc -l | grep -i -w ^apt # GREP PARTICULAR MODULE(APT) MODULE
To view the documentation for a module you can run the following command. Here I am viewing the documentation for the apt module which is the package manager module for Debian/Ubuntu-based distributions.
$ ansible-doc apt
Below image shows the documentation for the ansible apt module.
Ad hoc Command Syntax
There are a few inputs you have to provide when running the ad hoc command.
- You have to specify the targets(managed nodes). Either you can use the default "all/ungrouped" groups or user-defined groups.
- You have to pass the module name as an argument to the
- Every module accepts a set of options. Those options should be passed as arguments to -a flag. If there are multiple options then they should be enclosed within quotes.
$ ansible [group] -m [module] -a [module arguments]
You can combine other arguments we have seen in the previous sections into ad hoc commands.
Verify Connectivity using Ping Module
The first module you run after setting up ansible is the "ping" module. The ping module is used to verify if the connectivity is fine with the controller and managed nodes. If the connection is successful you will get a response as "ping : pong".
$ ansible all -m ping
You can also condense the output by using the
$ ansible all -m ping -o
Execute Commands through Shell Module
The shell module is used to execute any command that you can run over the terminal. It is simply like running the commands over a Linux terminal.
You should use the
-a flag and pass commands as arguments to the shell module.
$ ansible all -m shell -a "arguments"
Below are some of the commands that I ran through the ansible shell module.
$ ansible all -m shell -a "echo $USER"
$ ansible all -m shell -a "uptime"
$ ansible all -m shell -a "cat /etc/os-release | grep -i PRETTY_NAME"
$ ansible all -m shell -a "touch /tmp/abc.txt"
$ ansible all -m shell -a "ls -l /tmp/abc.txt"
Alternative to shell module you can also use the command module which is the default module in ansible. You can directly use the
-a flag and pass commands as the argument since the command module is the default module.
$ ansible all -m command -a "uptime" # EXCLUSIVELY PASSING COMMAND MODULE $ ansible all -a "uptime" # NOT USING -m TO PASS MODULE
The difference between shell and command module is with the command module you can access some special variables and cannot use pipes, redirections, and logical AND operators.
Run the following command and you will get an error.
$ ansible all -m command -a "test -f /etc/hosts && echo 'hosts file present'"
You can run the same command through the shell module and it will run fine.
$ ansible all -m shell -a "test -f /etc/hosts && echo 'hosts file present'"
Execute Scripts through Script Module
When you wish to execute any script(python, shell, etc.) you can use the script module which will copy the script from your controller machine to all the managed nodes then execute the script.
I have the following python code in my
import sys,os print("CURRENT PYTHON VERSION = ", sys.version_info) print("HOSTNAME = ", os.uname()) print("CURRENT DIRECTORY = ", os.getcwd())
Run the following command to use the script module to run the script. The script module supports extra arguments depending on how you are running your script. In my case, I am running a python script so I am trying to pass the extra argument "executable=python3" along with the script path.
$ ansible all -m script -a "/tmp/get_host_details.py executable=python3"
Package Management Modules
There are modules to work with OS package managers like
pacman, etc. Here I am using
apt since I am running Ubuntu. But the syntax is going to be the same for all the package managers with parameter differences. You should look at the respective documentation to know more about it.
To install packages you can run the following command and set the state to "present". You should choose
-become flag to run the module with
sudo privilege in the managed nodes. If you have set the password for the sudo user, then you should pass
-K along with the
-b flag which will prompt for the become password.
$ ansible all -m apt -a "name=cowsay,vim,cmatrix state=present" -b -K
To learn how privilege escalation works, take a look at our article using the link below.
To remove the packages you can run the following command and set the state to "absent".
$ ansible all -m apt -a "name=cowsay,vim,cmatrix state=absent" -b -K
Till now I have shown how to use different modules for different tasks. This might have given you a good understanding of how things work when you run ad hoc commands.
There are tons of other modules and this article will not be enough to go through all. So I suggest you to pick the module according to your use case and start practicing with the ad hoc commands.
When you execute ad hoc commands, you should have seen the output in three different colors. Each color has a meaning to it.
RED - Failure YELLOW - Success With Changes happened GREEN - Success but no changes happened
RED - Failure
If your task is failed, then it will be printed in red color.
YELLOW - Success with Changes
When the state is set to change, then the output will be in yellow color.
GREEN - Success but No Changes
When the object state is not changed, then the output will be in green color.
In this article we have discussed on what is ad hoc commands and how to use ad hoc commands in Ansible. As a beginner, ad hoc commands will give you a good understanding of how ansible uses modules to achieve a task. At the next level, you will start writing playbooks in YAML format which will be covered in detail in a separate article.Read Next: