Day 56 : Understanding Ad-hoc commands in Ansible

Sahil KaushalSahil Kaushal
2 min read

Ad-hoc commands in Ansible are used to run simple, one-time tasks on remote nodes without writing a playbook. They are quick and efficient for tasks that don't need to be repeated often.

What are Ad-hoc Commands?

Ad-hoc commands are executed using the ansible command-line tool. They allow you to run Ansible modules directly on the command line to perform tasks on one or more managed nodes. These commands are not saved for future use, making them ideal for quick, on-the-fly operations.

Syntax

The basic syntax for an ad-hoc command is:

ansible [pattern] -m [module] -a "[module options]"
  • [pattern]: Specifies the target hosts or groups from the inventory.

  • -m [module]: Specifies the Ansible module to use.

  • -a “[module options]”: Provides the arguments for the module.

Examples

  1. Ping all hosts:

     ansible all -m ping
    

    This command uses the ping module to check the connectivity of all hosts in the inventory.

  2. Reboot servers:

     ansible app -a "/sbin/reboot"
    

    This command reboots all servers in the app group.

  3. Copy a file:

     ansible webservers -m copy -a "src=/etc/hosts dest=/tmp/hosts"
    

    This command copies the /etc/hosts file to /tmp/hosts on all servers in the webservers group.

  4. Install a package:

     ansible all -m yum -a "name=httpd state=present"
    

    This command installs the httpd package on all hosts using the yum module.

Use Cases

Ad-hoc commands are useful for tasks such as:

  • Rebooting servers: Quickly reboot a group of servers.

  • Managing files: Copy, move, or delete files on remote nodes.

  • Managing packages: Install, update, or remove software packages.

  • Managing users and groups: Add or remove users and groups.

  • Managing services: Start, stop, or restart services.

  • Gathering facts: Collect information about remote nodes.

Advantages

  • Quick and easy: No need to write a playbook for simple tasks.

  • Flexible: Can be used with any Ansible module.

  • Declarative: Ensures the desired state is achieved without specifying the steps to get there.

Limitations

  • Not reusable: Ad-hoc commands are not saved for future use.

  • Limited scope: Best suited for simple, one-time tasks.

Conclusion

Ad-hoc commands in Ansible are a powerful tool for quickly performing tasks on remote nodes. They are especially useful for tasks that are not performed frequently enough to warrant writing a playbook. By understanding and utilizing ad-hoc commands, you can leverage the full power of Ansible for efficient and effective system management.

Thank you for reading😉.

0
Subscribe to my newsletter

Read articles from Sahil Kaushal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahil Kaushal
Sahil Kaushal