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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Run one Ansible ad hoc command against several servers by putting the servers in an inventory, selecting them with a host pattern, and supplying a module. The basic form is ansible <pattern> -i <inventory> -m <module> -a "<module arguments>". For example, this starts Apache on every host in the webservers group:

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

The inventory determines which machines exist and how they are grouped; the pattern determines which of those machines receive the task. Ansible contacts selected hosts in parallel, uses five simultaneous processes by default in the documented example, and lets you change concurrency with -f. SSH credentials, the remote user, and optional privilege escalation then determine whether the module can run.

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-task operation launched with the /usr/bin/ansible command-line tool against one or more managed nodes. It is useful when you need an immediate, isolated action: checking uptime, copying a file, starting a service, or gathering facts from a group of machines.

Unlike a playbook, an ad hoc command is not a reusable procedure. It has no durable task sequence, variables file, handlers, approval workflow, or regular audit structure. Treat it as a precise operational tool for work that is occasional or simple. When the same operation will be repeated, or when several steps must run in a defined order, move it into a playbook instead of building an increasingly long shell command.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

Build an inventory that represents your servers

An inventory is the list of managed nodes, their groups, and associated variables. Save an INI inventory such as this as inventory.ini:

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

[dbservers]
db01.example.com

Here, webservers and dbservers are groups. A command aimed at webservers reaches the three web hosts, while a command aimed at dbservers reaches the database host. The inventory can contain many groups; grouping by role, environment, or location lets you express a narrow target without typing every hostname.

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

Choose the inventory source

Pass the inventory path with -i on every command when it is not the default source:

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

The value after -i can be an inventory path or an inventory expression supported by your Ansible setup. Keep the inventory used for an operation explicit so that a similarly named group in another environment cannot receive the task by mistake.

Select several hosts with patterns

Ansible patterns are the targeting language between the inventory and the module. Start with the smallest pattern that proves the command works, inspect the result, and only then widen it.

Pattern What it selects Typical use
all Every host in the inventory. Gather facts or perform a deliberately global read-only check.
A single hostname One inventory host. Validate credentials and module arguments on one machine first.
host1,host2 The listed hosts, separated by commas. Run a task on a small, explicit set without creating a group.
webservers Every host in one group. Apply a web-tier operation to all web servers.
webservers:dbservers Hosts in either group. Use one command for two roles when the operation is appropriate to both.
webservers:&staging Hosts that are members of both groups. Limit a role to a particular environment.
webservers:!phoenix Web servers except the host or group named phoenix. Exclude a node undergoing maintenance.
Wildcard pattern Inventory hostnames or IP addresses matching the wildcard. Select a naming range when the inventory naming scheme is consistent.

Pattern syntax is evaluated against inventory names, not against an arbitrary list of machines on the network. A typo can produce no matching hosts or a different set than intended, so review the spelling and group membership before a state-changing command.

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.

Understand the command anatomy

The canonical structure is:

ansible <pattern> -i <inventory> -m <module> -a "<module arguments>"
  • ansible: invokes the ad hoc command-line client.
  • <pattern>: chooses hosts from the inventory.
  • -i <inventory>: identifies the inventory source.
  • -m <module>: selects the operation, such as ansible.builtin.command or ansible.builtin.copy.
  • -a "...": passes arguments understood by that module.

Arguments belong to the remote module, not to your local shell. Keep the complete argument string quoted so that local expansion does not alter variables, wildcard characters, pipes, or redirects before Ansible receives them.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Run a controlled first command

  1. Create or identify the inventory. Put the intended hosts in inventory.ini and confirm the group name you will use.
  2. Check one host with a harmless command. Use the command module to identify the remote account and operating-system identity:
ansible web01.example.com -i inventory.ini -m ansible.builtin.command -a "id"
  1. Test the whole group after the single-host check succeeds.
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uname -a"
  1. Review each host result. Continue only when every intended host is reachable and the output matches the expected account and platform.
  2. Apply the real operation with a purpose-built module. For example, use service to manage a service rather than embedding service commands in a shell string.

This progression separates inventory and SSH problems from module or application problems. It also limits the impact of a bad argument while you are still validating the command.

Control parallel execution with forks

Ansible processes multiple hosts concurrently. The official ad hoc example uses five simultaneous processes by default. If the selected group is larger, set the number of parallel forks with -f:

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

The documented worked example also shows a command aimed at an atlanta group with ten forks:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ansible atlanta -a "/sbin/reboot" -f 10

The number is a concurrency setting, not a performance guarantee. A higher fork count can increase CPU, memory, SSH, and network load on the controller and can make the managed servers handle more simultaneous work. Choose a value that your controller, network, and hosts can sustain. For a sensitive change, a smaller target pattern is often safer than simply increasing forks.

Supply SSH credentials and the correct remote user

Every selected host must be reachable through working SSH credentials before the module can execute. Select the remote login account with -u:

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

The command reports the identity of the account used on each host. This is an important check because a command that works for one account may lack the permissions or environment expected by another.

Use become for elevated operations

When the operation requires administrator privileges, enable privilege escalation with --become:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
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 or its short form -K so Ansible prompts for it:

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

Use escalation only when the module needs it. Running every read-only check as an administrator makes it harder to see which permissions an operation genuinely requires and increases the consequence of a targeting mistake.

Pick the module that matches the task

Module Best fit Important behavior Example
ansible.builtin.command A straightforward executable and its arguments. This is the default ad hoc module. It does not provide shell pipes, redirects, or other extended shell syntax. ansible ... -m ansible.builtin.command -a "uptime"
ansible.builtin.shell A command that genuinely needs shell syntax. Use it for constructs such as pipes or redirects; quote the argument so the local shell does not interpret it first. ansible ... -m ansible.builtin.shell -a "ps aux | grep httpd"
ansible.builtin.copy Copying a file or content to managed nodes. Expresses the desired file state and can preview a change in check mode. ansible ... -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"
ansible.builtin.service Starting or stopping a service. Uses a declarative state such as started, checking current state where supported. ansible ... -m ansible.builtin.service -a "name=httpd state=started"
ansible.builtin.setup Gathering facts from hosts. Collects system facts without requiring a separate command string. ansible all -i inventory.ini -m ansible.builtin.setup

Prefer the module whose purpose matches the requested state. A purpose-built module communicates intent and can make idempotent decisions, while a raw shell command generally leaves more interpretation and repeat-run behavior to you.

Practical multi-server commands

Run a read-only system check

To execute uname -a on every web server:

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

For a lightweight availability check, run uptime and increase forks only if the controller and hosts can handle the additional concurrency:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uptime" -f 10

Copy one file to every target

The copy module can transfer the same source file to each selected host:

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

src identifies the source and dest identifies the path on each managed node. Check the destination and the account being used before copying into a protected location.

Ensure a service is running

Use the service module to request the desired state:

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
ansible webservers -i inventory.ini -m ansible.builtin.service -a "name=httpd state=started"

The module checks the current state where supported instead of blindly issuing the same start operation every time. Add --become when the service manager requires elevated privileges.

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.

Gather facts from all hosts

To collect facts from every inventory host:

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

Use the all pattern intentionally: it includes database, staging, and other groups in the inventory, not just the web tier.

Use a shell pipeline only when it is required

A pipe belongs to the shell module, not the command module:

ansible webservers -i inventory.ini -m ansible.builtin.shell -a "ps aux | grep httpd"

If the operation can be expressed with copy, service, setup, or another purpose-built module, use that module instead. Shell syntax adds quoting and interpretation layers and can make repeat runs less predictable.

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

Preview changes and limit risk

Use check mode when the selected module supports it. The short option is -C, and the long option is --check. For example, preview a copy operation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ansible webservers -i inventory.ini -m ansible.builtin.copy -a "content=foo dest=/root/bar.txt" --check

For this documented example, check mode prints what Ansible would do without making the file change. Check-mode support is module-dependent, so read the behavior of the module you selected rather than assuming every command can be simulated perfectly.

Use a staged rollout

  • Start with one host or a very small comma-separated pattern.
  • Confirm the result and inspect any changed, failed, or unreachable host output.
  • Expand to the relevant group only after the command and privileges are proven.
  • Use an intersection such as webservers:&staging when an environment boundary matters.
  • Use an exclusion such as webservers:!phoenix when a known host must remain untouched.

This approach is especially important for state-changing commands, because an accurate module does not protect you from an inaccurate host pattern.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Troubleshoot the common failure points

No hosts are reached

Check the inventory path after -i, the spelling of the group, and the pattern syntax. A host must exist in the inventory for a pattern to select it. If you used a wildcard, confirm that it matches the inventory hostname or IP address you intended.

SSH authentication fails

Verify credentials for every target and confirm that the account named by -u is valid on all selected hosts. Test with a harmless id command before attempting a privileged or state-changing module. A group can contain hosts with different access requirements, so a credential that works on one member does not prove that the entire group is ready.

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

The operation needs more permissions

Run the command with --become and, when required, --ask-become-pass or -K. If a non-privileged read succeeds but the state change fails, compare the account and escalation options rather than replacing the module with an unrestricted shell command.

A pipe or redirect is treated as an argument

The command module does not implement extended shell syntax. Change to ansible.builtin.shell only when the pipe, redirect, or other shell feature is essential, and quote the complete argument string so the local shell does not expand it before Ansible receives it.

Different hosts return different results

Read each host’s status separately. Hosts can differ in operating-system packages, service names, permissions, or current state. A purpose-built module can account for current state where supported, but it cannot make an invalid service name or missing prerequisite valid on every machine.

Increasing forks makes the run worse

Reduce -f when the controller, network, or managed nodes become saturated. Ten forks is the documented example, not a universal optimum or benchmark. More simultaneous processes can increase contention and may lengthen completion time when a shared resource is the bottleneck.

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

Know when an ad hoc command should become a playbook

Move the work into a playbook when any of these requirements appears:

  • The command needs variables that differ by host, group, or environment.
  • Several tasks must run in a defined order.
  • A change should notify handlers or coordinate dependent services.
  • An approval, audit trail, or repeatable review is required.
  • The procedure will run regularly or be handed to other operators.
  • You need a reusable description of the desired state instead of a one-time command line.

Ad hoc commands are excellent for a single diagnostic or a rare, well-scoped intervention. Playbooks provide the reusable structure once the operation becomes a procedure. The same inventory groups, patterns, modules, users, and privilege decisions you validate with an ad hoc command carry over into that playbook.

A practical decision framework

Question If the answer is yes Recommended choice
Is this one immediate task on one or more known hosts? The action has no dependent steps. Use an ad hoc command with a narrow pattern.
Must the command run on a role or environment subset? Inventory groups express that boundary. Use a group, intersection, or exclusion pattern.
Does the task require shell-only syntax? A pipe or redirect is unavoidable. Use ansible.builtin.shell; otherwise prefer a purpose-built module.
Does the task require administrator rights? The login account cannot perform it directly. Use --become, adding -K when a prompt is needed.
Will the task be repeated or expanded? Variables, ordering, handlers, approvals, or auditing are involved. Write a playbook rather than extending an ad hoc command.
Could a simultaneous run overload the environment? The group is large or the operation is resource-intensive. Choose a conservative -f value and stage the target pattern.

Quick reference

# Check one host
ansible web01.example.com -i inventory.ini -m ansible.builtin.command -a "id"

# Run on a group
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uname -a"

# Select two explicit hosts
ansible host1,host2 -i inventory.ini -m ansible.builtin.command -a "uptime"

# Use ten parallel forks
ansible webservers -i inventory.ini -m ansible.builtin.command -a "uptime" -f 10

# Log in as a named user
ansible webservers -i inventory.ini -u deploy -m ansible.builtin.command -a "id"

# Escalate privileges and prompt for the become password
ansible webservers -i inventory.ini -u deploy --become -K -m ansible.builtin.command -a "id"

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

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

# Gather facts
ansible all -i inventory.ini -m ansible.builtin.setup

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

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.