Ansible Curriculum
Ad Hoc Command Basics
Common Ad Hoc Commands
On this page
Subtopic•Ad Hoc Command Basics

What Are Adhoc Commands

Ansible playbooks are designed for configuration management and multi-task deployments. However, you often need to perform quick, one-off tasks across your servers, such as rebooting a group of nodes, checking server disk space, or restarting a service.

Writing a complete YAML playbook for a single task can be slow.

To solve this, Ansible supports Ad-Hoc Commands. An ad-hoc command is a single-line command that executes a single module against your target hosts directly from your terminal.

In this guide, we will explore the purpose of ad-hoc commands, examine common use cases, and run simple commands to check host status.

Ad-Hoc Commands Execution Model

Diagram

Core Use Cases for Ad-Hoc Commands

Ad-hoc commands are useful for:

  • Infrastructure Audits: Check uptime, verify memory utilization, or inspect disk space across multiple host groups.
  • Service Management: Start, stop, or restart service daemons (like Nginx or Docker) across a group of servers.
  • File Management: Copy configuration files or delete temporary logs quickly.
  • Package Management: Install security updates or packages across all nodes concurrently.

1. Quick Example: Querying Server Uptime

To check the uptime of all hosts in the webservers group using the shell module, run:

ansible webservers -m ansible.builtin.shell -a "uptime"

Output:

web-prod-01 | CHANGED | rc=0 >>
 19:42:01 up 45 days,  4:12,  1 user,  load average: 0.05, 0.02, 0.01

web-prod-02 | CHANGED | rc=0 >>
 19:42:01 up 12 days,  8:45,  1 user,  load average: 0.12, 0.08, 0.05

The output shows the status of each host, indicating whether the command changed the system state (e.g. CHANGED or SUCCESS) and printing the execution results.


Summary

Ad-hoc commands allow you to execute single-task modules quickly across your servers directly from the command line, avoiding the need to write playbooks for one-off tasks. In the next section, we will cover ad-hoc command syntax.

←Previous ModuleInventory