Skip to main content
Ansible Configuration
CHAPTER 04

Ansible Ad-Hoc Commands

Updated: May 15, 2026
20 min read

# CHAPTER 4

Ansible Ad-Hoc Commands

1. Introduction

Ansible is famous for its Playbooks—complex, reusable YAML scripts that configure entire infrastructures. However, sometimes you don't need a complex script. Sometimes you just need to restart a frozen service on 50 servers *right now*, or quickly check how much hard drive space is left across your entire web fleet. For these rapid, one-off tasks, we use Ad-Hoc Commands. In this chapter, we will master the Ansible command line, exploring core modules to execute instant infrastructure modifications without writing a single file of code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the purpose and syntax of Ansible Ad-Hoc commands.
  • Understand the difference between the command, shell, and raw modules.
  • Execute ad-hoc commands with elevated privileges using --become.
  • Utilize the apt / yum modules for rapid package management.
  • Utilize the service module to restart infrastructure components globally.

3. Beginner-Friendly Explanation

Imagine you are the manager of a massive kitchen with 20 chefs.
  • The Playbook: You spend hours writing a highly detailed recipe book for a 5-course meal, print 20 copies, and distribute them to the chefs to follow precisely. (Complex, repeatable, planned).
  • The Ad-Hoc Command: You notice a fire in the oven. You grab a megaphone and scream: "EVERYONE TURN OFF YOUR OVENS RIGHT NOW!" (Instant, one-time, urgent).

Ad-Hoc commands are your megaphone. They allow you to execute single, immediate actions across your entire inventory.

4. The Anatomy of an Ad-Hoc Command

The syntax for an ad-hoc command is always the same: ansible [target] -m [module_name] -a "[arguments]"
  1. 1. Target: The group from your inventory (e.g., webservers, databases, all).
  1. 2. -m (Module): The specific tool you want Ansible to use.
  1. 3. -a (Arguments): The instructions you pass to the tool.

Example 1: The command module (The Default) Find out the uptime of all web servers:

bash
1
ansible webservers -m command -a "uptime"

*(Note: -m command is the default module. If you omit -m, Ansible assumes you mean command)*.

5. Privilege Escalation (--become)

If you try to install a package or restart a service as a normal user, Linux will deny you permission. You need sudo access. In Ansible, we use the --become flag (short for -b) to execute the command as the root user.

Example 2: The apt module (Package Management) Install the nginx web server on all Ubuntu machines.

bash
1
ansible webservers -m apt -a "name=nginx state=present" --become

*(Ansible logs in as your normal user, escalates to root using --become, and runs apt-get install nginx).*

Example 3: The service module (Service Management) Restart the Nginx service on all web servers.

bash
1
ansible webservers -m service -a "name=nginx state=restarted" -b

6. Mini Project: Automate Linux Package Updates

A zero-day security vulnerability has been announced for the openssl package. You need to update this package immediately on all 100 servers in your data center. Doing this manually via SSH would take hours. Let's do it in 5 seconds.

Step-by-Step Walkthrough:

  1. 1. Ensure your inventory.ini has an [all] group containing your servers.
  1. 2. Open your terminal.
  1. 3. Execute the ad-hoc command using the package manager module (assuming Ubuntu/Debian):

bash
1
ansible all -m apt -a "name=openssl state=latest update_cache=yes" -b

Observation: Ansible will connect to all 100 servers simultaneously. It will run apt-get update (update_cache=yes), check the current version of openssl, and if an update is available, download and install it as the root user (-b). *You just secured your entire data center with one line of text.*

7. Real-World Scenarios

A monitoring alert went off at 3:00 AM indicating that the "Backend Application" API was returning 500 Server Errors. The DevOps engineer woke up and realized the application's log files had grown so large they filled up the entire hard drive on all 12 backend servers, crashing the application. Instead of writing a complex playbook, the engineer used an ad-hoc command: ansible backend -m shell -a "rm -rf /var/log/app/*.log" -b Within 10 seconds, the massive log files were deleted across all 12 servers simultaneously. The engineer then restarted the service with another ad-hoc command: ansible backend -m service -a "name=backend-api state=restarted" -b The entire incident was resolved in under 60 seconds from the command line.

8. Best Practices

  • command vs shell: The command module is extremely secure, but it cannot process Linux environment variables or pipelines (like |, >, &&). If you absolutely need to use a pipeline (e.g., echo "hello" > file.txt), you must use the shell module. However, avoid the shell module if possible, as it is vulnerable to shell injection if you pass untrusted variables into it.

9. Security Recommendations

  • The Danger of Ad-Hoc: Ad-Hoc commands leave very little audit trail. Because they are just typed into a terminal, they are not saved in GitHub, and your team doesn't know what you did. For routine maintenance or complex configurations, always use Playbooks. Ad-Hoc commands should be reserved exclusively for read-only information gathering (like checking disk space) or emergency triage.

10. Troubleshooting Tips

  • Missing Sudo Password: If your --become command fails with a "Missing sudo password" error, it means your Linux user requires a password to execute sudo commands. You must append the -K (or --ask-become-pass) flag to your ad-hoc command. Ansible will prompt you to type the sudo password once before executing.

11. Exercises

  1. 1. Write the ad-hoc command to reboot all servers in the databases group. (Hint: look up the reboot module).
  1. 2. What is the operational purpose of the --become flag?

12. FAQs

Q: What if I use CentOS or RedHat instead of Ubuntu? A: You cannot use the apt module on RedHat; it will fail because RedHat uses yum. You would use -m yum -a "name=nginx state=present". (Ansible also provides a generic -m package module that tries to automatically guess which OS it is on!).

13. Interview Questions

  • Q: Differentiate the operational limitations between the command module and the shell module in Ansible Ad-Hoc execution. Provide a scenario where the shell module is strictly required.
  • Q: An engineer proposes using Ad-Hoc commands for the daily backup script deployment. Explain why this violates Infrastructure as Code principles and advocate for the correct Ansible architecture.

14. Summary

In Chapter 4, we wielded the raw power of the Ansible execution engine. We learned how to bypass complex YAML scripting to execute instantaneous, simultaneous actions across massive infrastructure fleets using Ad-Hoc commands. We mastered the syntax of targeting specific inventory groups, passing arguments to distinct modules (apt, service), and seamlessly elevating our execution privileges to root utilizing the --become flag. While establishing that Ad-Hoc commands are critical for emergency triage, we acknowledged their lack of auditability, pointing us toward the true core of Ansible automation.

15. Next Chapter Recommendation

Megaphones are great for emergencies, but true automation requires repeatable, version-controlled sheet music. It is time to write our first script. Proceed to Chapter 5: Ansible Playbooks Fundamentals.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·