Yes, you can run a single command on a remote machine using Ansible by leveraging its built-in command or shell modules, which connect to targets via SSH without requiring pre-installed Ansible on the remote host. This is done through playbooks, ad-hoc commands, or inventory-based execution, with secure authentication handled via SSH keys or passwords.
Background: What Ansible Remote Execution Actually Does
Ansible’s remote execution capabilities rely on its agentless architecture, where commands are pushed to target systems via SSH (or WinRM for Windows). Unlike agents like Puppet or Chef, Ansible doesn’t require software pre-installed on the remote machine—just a working SSH connection. This simplicity makes it ideal for quick tasks like running diagnostics, installing packages, or configuring services on remote servers.
The core mechanism uses the command module for simpler shell commands (without shell interpretation) and the shell module for more complex scripts (which can use shell features like pipes or variables). Both modules accept parameters like args, chdir, and environment to fine-tune behavior.
How It Works Step-by-Step
To run a command remotely, you need:
- Ansible installed locally (on the control node).
- A remote host configured in the
inventory file(e.g.,hosts) with valid SSH credentials. - Either an ad-hoc command (one-off execution) or a playbook (reusable automation).
Option 1: Ad-Hoc Command Execution
For quick, one-off commands, use the ansible CLI directly. Example:
ansible all -m command -a "uptime" -i inventory.ini
Where:
alltargets every host in the inventory.-m commandspecifies the module (alternatively, useshell).-a "uptime"is the command to run.-i inventory.inipoints to your inventory file.
Option 2: Playbook for Reusable Automation
For repeatable tasks, define a playbook (YAML file) like remote_run.yml:
---
- name: Run a command on remote hosts
hosts: webservers
tasks:
- name: Check system uptime
command: uptime
register: uptime_output
- name: Print uptime result
debug:
var: uptime_output.stdout
Run it with:
ansible-playbook remote_run.yml
How to Choose Between command and shell
Select the module based on your needs:
- Use
commandwhen:- The command is a single executable (e.g.,
ls /tmp). - You avoid shell features like variables or pipes.
- Security is a priority (no shell parsing overhead).
- The command is a single executable (e.g.,
- Use
shellwhen:- The command requires shell features (e.g.,
grep "error" /var/log/syslog). - You need to use environment variables or redirection.
- The command is a script (e.g.,
./script.sh).
- The command requires shell features (e.g.,
Key Difference: The command module runs the command directly (e.g., /usr/bin/ls), while shell invokes the shell (/bin/sh) to interpret it. This affects security and behavior.
Common Problems and Fixes
Even simple remote commands can fail. Here are troubleshooting tips:
Problem 1: Permission Denied or SSH Issues
Symptoms: Commands fail with Permission denied (publickey) or Host key verification failed.
- Verify SSH keys are set up between the control node and remote hosts.
- Use
ansible_ssh_common_argsin your inventory to debug: - Check
~/.ssh/configfor host-specific settings.
- ansible_ssh_common_args='-vvv'
Problem 2: Module-Specific Errors
Example: The error was: /bin/sh: 1: /path/to/script.sh: Permission denied.
- If using
shell, ensure scripts are executable: - For
command, specify the full path explicitly.
ansible all -m shell -a "chmod +x /path/to/script.sh"
Problem 3: Environment Variables Not Respected
If a command fails due to missing environment variables (e.g., PATH), use the environment parameter:
ansible all -m shell -a "my_script.sh" -e "PATH=/custom/path:$PATH"
Comparisons: Ansible vs. Other Tools
While Ansible is popular for remote execution, alternatives include:
| Tool | Remote Execution Method | Pros | Cons |
|---|---|---|---|
| SSH | Direct SSH commands | No setup; built into Linux | Manual; no automation |
| Fabric | Python-based (like Ansible) | Lightweight, scriptable | Less enterprise-friendly |
| Puppet/Chef | Agent-based configuration | Declarative, idempotent | Complex setup; agent overhead |
Ansible stands out for its simplicity and agentless design, making it ideal for ad-hoc tasks or hybrid workflows.
Cost and Licensing
Ansible is open-source under the GPLv3 license, with a free tier available for unlimited hosts. For enterprise features like:
- Ansible Tower (now Red Hat Ansible Automation Platform)
- Audit logs and RBAC
- Scaled execution
Red Hat offers paid subscriptions starting at no specific public pricing (consult Red Hat for quotes). The open-source version covers 90% of use cases without cost.
Safety: Mitigating Risks in Remote Execution
Running arbitrary commands remotely introduces risks. Follow these practices:
1. Principle of Least Privilege
- Use SSH keys instead of passwords to avoid credential leaks.
- Restrict SSH access with
AllowUsersin/etc/ssh/sshd_config.
2. Validate Commands Before Running
- Test commands locally first using
ansible localhost. - Use
become: yescautiously (e.g.,sudoprivileges).
3. Limit Inventory Scope
- Avoid wildcards like
allunless necessary. - Use groups (e.g.,
webservers) to target specific hosts.
4. Use Idempotent Modules Where Possible
- Prefer
package,file, orservicemodules over rawshellcommands. - Add
check_mode: yesto dry-run changes.
Alternatives to Raw Commands
For production environments, consider these Ansible modules as safer alternatives:
package: Install/remove packages (e.g.,yum name=nginx state=present).file: Manage files/folders (e.g.,path=/tmp/test state=touch).service: Control services (e.g.,name=nginx state=restarted).copy: Push files to remote hosts.
These modules handle edge cases (e.g., package dependencies, file permissions) and are more reliable than raw shell commands.
Frequently Asked Questions
How do I run a command as root without a password prompt?
Use the become directive in playbooks or the -b flag in ad-hoc commands. For passwordless sudo, configure /etc/sudoers to allow Ansible’s user (e.g., ansible ALL=(ALL) NOPASSWD: ALL). Example:
ansible all -m command -a "whoami" -b
Can I run Ansible commands on Windows remotely?
Yes, using the win_command or powershell modules. First, ensure WinRM is enabled on Windows targets. Example:
ansible windows_hosts -m win_command -a "Get-Process"
WinRM requires port 5985 (HTTP) or 5986 (HTTPS) to be open.
What’s the difference between -a and args in Ansible?
The -a CLI flag and args YAML parameter serve the same purpose: passing command arguments. In a playbook, use args: "uptime", while in the CLI, use -a "uptime". Both pass the string directly to the module.
How do I see the output of a failed remote command?
Use the failed_when directive to capture errors or set register: var_name to inspect output. Example:
- name: Run risky command
command: /bin/nonexistent
register: result
ignore_errors: yes
- name: Show output even if failed
debug:
var: result.stdout_lines
Check result.stderr_lines for error details.
Is it safe to run shell commands with sudo?
Running shell commands with elevated privileges (become: yes) is risky if:
- The command is arbitrary (e.g.,
rm -rf /). - The user lacks proper training.
Mitigate risks by:
- Using
become_method: sudowith restrictedsudoersrules. - Avoiding
shellfor critical tasks; use idempotent modules instead.
Why does Ansible sometimes hang when running remote commands?
Common causes include:
- Network latency or firewall blocking SSH (port 22).
- Long-running commands (e.g.,
cronjobs) without timeouts. - SSH timeouts due to
GSSAPIAuthenticationorServerAliveIntervalmisconfigurations.
Fixes:
- Add
timeout: 30to the task. - Increase
ansible_ssh_timeoutin inventory (e.g.,ansible_ssh_timeout=60). - Check remote server logs (
/var/log/securefor SSH errors).