Ansible Ad hoc command examples

Ansible adhoc command is an easy way to understand the basics of Ansible. They are useful when you want to run simple tasks like rebooting all servers, changing the permission of a particular file in multiple systems etc. You don’t have to create a file for running an Adhoc command.You can run a basic Ansible AdHoc command as easy as executing a ping command. To learn more about how to execute adhoc commands refer here.

ansible adhoc ping

One of the most simple commands used in Ansible is the ping module. It can be used to check the SSH connection between the Ansible control machine and the target machines. This is not ICMP ping.

ansible servers -m ping -i inventory.ini

ansible ad hoc grep

ansible loc -m shell -a "grep -ir 'add apt' *.yaml" -i inventory.ini

ansible ad hoc apt

ansible loc -m apt -a "name=nginx state=present update_cache=true" -i inventory.ini -s
ansible loc -m apt -a "name=nginx state=absent" -i inventory.ini -s

ansible ad hoc yum

ansible loc -m yum -a "name=nginx state=present update_cache=true" -i inventory.ini -s
ansible loc -m yum -a "name=nginx state=absent" -i inventory.ini -s

ansible ad hoc dnf

ansible loc -m dnf -a "name=httpd state=present" -i inventory.ini -s
ansible loc -m dnf -a "name=httpd state=absent" -i inventory.ini -s

ansible ad hoc service

ansible loc -m service -a "name=nginx state=started" -i inventory.ini -s
ansible loc -m service -a "name=nginx state=stopped" -i inventory.ini -s

ansible ad hoc systemctl

ansible loc -m systemd -a "name=nginx state=started" -i inventory.ini -s
ansible loc -m systemd -a "name=nginx state=stopped" -i inventory.ini -s

ansible ad hoc lineinfile

ansible loc -m lineinfile -a "dest=/etc/ansible/ansible.cfg regexp='inventory' state=absent" -i inventory.ini -s
ansible ad hoc reboot
ansible servers -m shell -a "reboot" -i inventory.ini -s
ansible ad hoc shutdown
ansible servers -m shell -a "shutdown +1 'Upgrading hardware'" -i inventory.ini -s