Ansible came to the market as a Simple IT automation tool for server/infrastructure management. Being Simple, agentless, pythonic and many more features to count on it also supports ad-hoc commands.
The Ad-Hoc command is the one-liner ansible command that performs one task on one or more managed nodes. Ad-hoc commands are quick and easy, but they are not reusable.
Ad-hoc commands are great for a very particular task or for the tasks you repeat rarely.For example doing SCP on server/machine in aws group.
$ ansible aws -i ./hosts -m copy -a "src=data.txt dest=/home/ubuntu/" -u ubuntu
An ad-hoc command looks like this:
$ ansible [pattern] -m [module] -a "[module options]"
Ad-hoc tasks can be used to reboot servers, copy files, manage packages and users, and much more. You can also use any Ansible module in an ad-hoc task. So lets see some of the use cases :
Here file '/etc/demo' from the 'aws' server to the local directory called 'backup'.
ansible aws -m fetch -a 'src=/etc/demo dest=/home/knoldus/backup/ flat=yes'
- Install Package
ansible aws -m apt -a "name=nginx state=latest" --become
- Remove package
ansible aws -m apt -a 'name=nginx state=absent purge=yes' --become
Facts can be used for implementing conditional statements in playbook.
$ ansible aws -m setup
$ ansible aws -m service -a 'name=nginx state=started enabled=yes' --become
$ ansible aws -m service -a 'name=nginx state=stopped' --become
$ ansible aws -a "uptime"
$ ansible -i ./hosts -m ping aws
Ad hoc is latin words refers to something done for a very precise and particular purpose. As the word suggests, ansible ad hoc commands are written for a very particular task.
So, that was all about Ansible Ad-hoc Commands.