Understanding Ad-hoc commands in Ansible

Understanding Ad-hoc commands in Ansible

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 handy when you want to perform a quick task.

Task-01

  • Write an ansible ad hoc ping command to ping 2 servers from inventory file

ansible server1:server2 -m ping

  • Write an ansible ad hoc command to check uptime

ansible -i /path/to/inventory/file all -m command -a uptime

If your inventory is in the default location (/etc/ansible/hosts or ~/.ansible.cfg) you can omit the -i option and the path altogether.

  • Ansible ad hoc command to check the amount of free memory or the amount of memory used by hosts.

ansible all -a "free -m"

  • Ansible ad hoc command to get physical memory allocated to the host

ansible all -m shell -a "cat /proc/meminfo|head -2"

  • Ansible command to check the disk space on all hosts in an inventory file

ansible all -m shell -a 'df -hT'

Ansible command to list all the running processes on a specific host in an inventory file

ansible all -m shell -a "ps aux"

Ansible command to run a shell command with sudo on all hosts in an inventory file

ansible all -m shell -a "sudo apt-get update"

Ansible command to show all 2 servers’ python versions.

ansible all -m shell -a "sudo python3 --version"

Ansible command to check the status of a specific service on all hosts in an inventory file

ansible all -m service -a "name=apache"

The following ad hoc command with copy module copies the file from Src location on the local control machine to the specified location on the remote server

ansible -i inventory_file all -m copy -a 'src=/local/path/to/file dest=/remote/path/to/file mode=0644'

First create a simple text file at any location, here create a text file at /home/ubuntu location with name file.txt.

Check if the file is successfully copied to all the servers with the ‘sudo ls command’

ansible all -m shell -a 'sudo ls /home/ubuntu'

Create a file with 755 permission using ansible ad hoc commands

ansible all -m file -a "path=/home/ubuntu/ansible state=directory mode=0755" -b