Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Manage Multiple Servers With Ansible Ad Hoc Commands

Run one Ansible task across many servers safely. This guide covers inventory patterns, parallel forks, SSH credentials, privilege escalation, module selection, check mode, practical commands, and the point where an ad hoc command should become a playbook.
Length10 min Posted Quest giverVGSources Team

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Ansible’s /usr/bin/ansible command with an inventory pattern, a module, and module arguments to run one task on several servers. The basic form is ansible <pattern> -i <inventory> -m <module> -a "<module arguments>". The inventory defines your servers; the pattern determines which of them receive the task.

This guide shows how to build the inventory, select hosts precisely, control parallel execution, authenticate over SSH, use privilege escalation, choose the right module, preview changes, diagnose failures, and decide when an ad hoc command should become a playbook.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What an Ansible ad hoc command does

An ad hoc command is a one-off Ansible operation launched from the controller with the ansible CLI. The official description is precise: it automates a single task on one or more managed nodes. Ansible connects to the selected hosts, runs the requested module, collects each host’s result, and reports success, change, or failure.

The canonical command is:

ansible <pattern> -i <inventory> -m <module> -a "<module arguments>"
  • <pattern> selects hosts from the inventory.
  • -i supplies an inventory file, directory, or other inventory source.
  • -m chooses the module.
  • -a passes that module’s arguments.

For example, this starts the HTTP service on every host in the webservers group:

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
ansible webservers -i inventory.ini -m ansible.builtin.service -a "name=httpd state=started"

Ad hoc commands are best for an occasional check, a quick, controlled change, or learning how a module behaves. They are not a replacement for a documented, repeatable deployment process.

Build an inventory that represents your servers

An inventory is the source of truth for managed nodes, their groups, and associated variables. Put hosts into meaningful groups so that a command can target a role, environment, or region instead of an improvised list of addresses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A minimal INI inventory

[webservers]
web01.example.com
web02.example.com
web03.example.com

[dbservers]
db01.example.com

Save that content as inventory.ini. The group names become usable patterns. To run a harmless identity check against all web servers:

ansible webservers -i inventory.ini -m ansible.builtin.command -a "id"

Before making changes, confirm that Ansible can read the inventory and reach the intended machines. A command that names the wrong inventory can still succeed—on the wrong hosts—so keep the -i option explicit when more than one inventory source exists.

Inventory design that scales beyond a few hosts

  • Use groups that describe function, such as webservers, dbservers, or monitoring.
  • Use separate groups for environments such as staging and production when the same role exists in both.
  • Keep hostnames stable. If addresses change, update the inventory rather than scattering IP addresses through command history.
  • Store connection variables in the inventory or in Ansible’s variable files when every host in a group shares them; use -u for a one-off remote-user override.

Select several servers with patterns

The pattern is the safety boundary for an ad hoc command. Read it as a set expression and verify that it matches exactly the hosts you intend to affect.

Pattern Meaning Example
all Every host in the selected inventory ansible all -i inventory.ini -m ansible.builtin.setup
One host A single inventory hostname ansible web01.example.com -i inventory.ini -m ansible.builtin.command -a "hostname"
host1,host2 A comma-separated ad hoc host list ansible web01.example.com,web02.example.com -i inventory.ini -m ansible.builtin.command -a "uptime"
One group Every host in a group ansible webservers -i inventory.ini -m ansible.builtin.command -a "uptime"
group1:group2 The union of two groups ansible webservers:dbservers -i inventory.ini -m ansible.builtin.command -a "uptime"
group:&group The intersection: hosts present in both groups ansible webservers:&staging -i inventory.ini -m ansible.builtin.command -a "uptime"
group:!host The group minus an excluded host or subgroup ansible webservers:!phoenix -i inventory.ini -m ansible.builtin.command -a "uptime"
Wildcard Inventory hostnames or IP addresses matching a wildcard ansible 'web*.example.com' -i inventory.ini -m ansible.builtin.command -a "uptime"

Quote patterns containing shell metacharacters such as !, *, or & when your local shell could interpret them. A narrow pattern is safer for the first run: target one host, inspect the result, then widen to the group.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control parallel execution with forks

Ansible communicates with multiple hosts in parallel. The ad hoc documentation demonstrates five simultaneous processes by default and shows -f 10 to increase the number of parallel forks:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uptime" -f 10

The number is a concurrency setting, not a performance guarantee. A larger fork count can shorten a wait when the controller, network, and targets have capacity, but it also increases CPU, memory, connection, and service load. Ten forks against a small controller or a fragile set of servers may be slower or less reliable than five.

Choosing a practical fork count

  • Start with the documented default behavior or a small value such as -f 5.
  • Increase gradually for a large group, watching controller load, SSH connection limits, and the service being changed.
  • Use a lower value when a task is disruptive, resource-intensive, or likely to overload a shared dependency.
  • Remember that forks control how many hosts are processed concurrently; they do not change the task’s order within a host or make an unsuitable module safe.

The documented five-process default and ten-fork example are operational examples, not benchmark results for your hardware or network.

Prepare SSH authentication and privilege escalation

Every target must be reachable over SSH with credentials that Ansible can use. Test access before changing state, and make sure the account has the permissions required by the module.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Select the remote login account

Use -u when the remote account is not your local username:

ansible webservers -i inventory.ini -u deploy -m ansible.builtin.command -a "id"

The result should show the expected remote user on each host. A failure on one host does not prove that the others are unreachable; read the per-host output and correct the account, key, host name, or SSH configuration indicated by the error.

Run a command with become

For operations requiring root or another elevated account, add --become:

ansible webservers -i inventory.ini -u deploy --become -m ansible.builtin.command -a "id"

If the escalation method needs a password, add --ask-become-pass, also written as -K:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
ansible webservers -i inventory.ini -u deploy --become -K -m ansible.builtin.command -a "id"

Use the least-privileged login account that can perform the task, and escalate only for the operation that needs it. A successful SSH login without --become can still fail when writing to a protected path or managing a system service.

Choose a module that matches the operation

The default ad hoc module is ansible.builtin.command. Prefer a purpose-built module when one expresses the desired state because it can understand the current state and avoid unnecessary changes.

Module Use it for Important detail
ansible.builtin.command A direct executable and its arguments It does not provide shell pipes, redirects, glob expansion, or other shell syntax.
ansible.builtin.shell A command that genuinely needs shell features Use only when pipes, redirects, command substitution, or shell operators are required; quote arguments carefully.
ansible.builtin.copy Copying a file or supplying file content It can compare the destination and report whether a change is needed.
ansible.builtin.service Starting, stopping, or otherwise managing a service Express the desired state, such as state=started, rather than issuing a distribution-specific service command.
ansible.builtin.setup Gathering facts from managed nodes Useful for checking what Ansible can learn from every target before a later decision.

Command versus shell

This command runs an executable directly:

ansible webservers -i inventory.ini -m ansible.builtin.command -a "uname -a"

If you need a pipeline or redirect, select shell explicitly:

ansible webservers -i inventory.ini -m ansible.builtin.shell -a "df -h / | tail -n 1"

Keep the entire module argument string correctly quoted. Otherwise, your local shell may expand a wildcard, substitute a variable, or interpret a pipe before Ansible sends the command to the remote host.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful multi-server ad hoc recipes

Check kernel and uptime on a group

ansible webservers -i inventory.ini -m ansible.builtin.command -a "uname -a"
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uptime"

These read-only checks are good first runs because they verify selection, SSH access, and module execution without changing configuration.

Copy one file to every selected host

ansible webservers -i inventory.ini -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"

src is resolved on the controller and dest is on each managed host. Confirm that the source exists locally and that the remote account can write the destination.

Ensure a service is running

ansible webservers -i inventory.ini -m ansible.builtin.service -a "name=httpd state=started"

The service module describes the desired state. On hosts where the service is already running, Ansible can report no change instead of blindly restarting it.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Gather facts everywhere

ansible all -i inventory.ini -m ansible.builtin.setup

This collects facts from all inventory hosts. Use a narrower pattern when the inventory includes machines that are offline, unusually slow, or outside the scope of your check.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preview changes and apply them safely

Use check mode when the selected module supports it. For example, the documentation demonstrates a copy operation with --check:

ansible webservers -i inventory.ini -m ansible.builtin.copy -a "content=foo dest=/root/bar.txt" --check

The short form is -C. In this example Ansible reports what it would do without making the file change. Check mode is a preview, not a universal simulation: support and the detail of the prediction depend on the module.

A controlled rollout sequence

  1. Inspect the inventory. Confirm the file, group names, hostnames, and any connection variables.
  2. Start with one host. Use an explicit hostname and a read-only command such as id or uptime.
  3. Confirm the account and privilege. Add -u and --become only as needed, then verify the resulting identity.
  4. Run check mode. Use --check for a module that supports it and inspect every reported host.
  5. Expand the pattern. Move from one host to a staging intersection or small group before selecting a broad group.
  6. Set an appropriate fork count. Keep the default behavior for a small operation; increase with -f only after considering controller and target capacity.
  7. Review output. Investigate unreachable, failed, changed, and skipped results separately rather than assuming a group-wide success.

Use a purpose-built module instead of shell whenever possible. It makes intent clearer and usually gives Ansible enough information to determine whether a change is necessary.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Diagnose common failures

“No hosts matched”

The pattern did not resolve to an inventory host. Check spelling, group names, wildcard quoting, and the inventory selected by -i. A group intersection returns only hosts present in both groups, so an empty intersection is expected when the inventory does not classify a host in both places.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SSH or unreachable errors

Verify the hostname resolves, the SSH service is reachable, the key or password is available, and the account supplied with -u exists on every target. Test a single host first to isolate network or credential problems from pattern mistakes.

Permission denied

The login account may be valid but lack permission for the requested action. Use --become and, when necessary, -K for an escalation password. Also verify that the configured sudo or other escalation policy permits that account to run the operation.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

The command behaves differently than expected

If a pipe, redirect, wildcard, or variable was intended for a remote shell, command will not provide it. Switch to ansible.builtin.shell only for that requirement, and quote the argument so the local shell does not consume the syntax first.

Only some hosts changed

Ansible reports results per host. One machine may be unreachable, lack the package or service named in the arguments, or have a different permission policy. Read the individual error, correct the underlying difference, and rerun against the affected host or a deliberately narrowed pattern.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The operation is too slow

Check whether the delay comes from SSH connection setup, the remote task, or a saturated target. Increase -f cautiously; more forks can add load and do not guarantee faster completion. For a disruptive operation, reducing concurrency may be the safer choice.

Know when to replace the command with a playbook

An ad hoc command is intentionally not reusable. Move the procedure into a playbook when it needs variables, multiple ordered tasks, handlers, approvals, auditing, or regular execution. A playbook also gives you a durable place to document the target groups, become policy, and expected end state.

Need Ad hoc command Playbook
One occasional task Well suited Usually unnecessary overhead
Precise host or group selection Pattern on the command line Hosts declaration plus optional command-line limit
Parallelism -f for the invocation Playbook execution controls and strategy settings
Privilege -u, --become, and -K Documented play or task-level become settings
Variables and ordering Hard to maintain in a long shell command Native structure for variables and ordered tasks
Handlers, approvals, and audit trail Not reusable by design Designed for repeatable, reviewable automation

Do not turn every quick diagnostic into a playbook. The boundary is repeatability and complexity: once people need to reconstruct the command from history, the operation has outgrown ad hoc execution.

A compact pre-flight checklist

  • Is the intended inventory selected with -i?
  • Does the pattern match exactly the hosts you intend to touch?
  • Have you tested one target with a read-only command?
  • Is the SSH login account correct, and is -u required?
  • Does the task need --become or -K?
  • Is the selected module appropriate, or are you using shell only because shell syntax is necessary?
  • Does the module support --check, and have you reviewed the preview?
  • Can the controller, network, and targets handle the chosen -f value?
  • Should this operation be captured as a playbook instead?

With those checks in place, the workflow is straightforward: inventory defines the servers, the pattern selects them, the module expresses the task, forks determine concurrency, and SSH plus become determine whether each host can carry it out.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.