Running Ansible Ad-hoc Commands
Introduction
Ansible is a powerful automation tool that allows you to manage and configure your infrastructure. While most Ansible operations are done using playbooks, there are scenarios where you might want to run quick, one-off tasks. This is where Ansible ad-hoc commands come in handy. In this tutorial, we will cover how to run ad-hoc commands using Ansible from start to finish, complete with detailed explanations and examples.
Prerequisites
Before you start running Ansible ad-hoc commands, you need to ensure the following prerequisites are met:
- Ansible is installed on your control machine.
- You have SSH access to the target machines.
- Your Ansible inventory is properly configured.
Basic Syntax
The basic syntax for running an Ansible ad-hoc command is as follows:
Here:
pattern
specifies the hosts or group of hosts the command should be run against.module
is the Ansible module to use. For example,ping
,command
,shell
, etc.module options
are the options to pass to the module.
Examples of Ad-hoc Commands
Ping All Hosts
To check connectivity to all hosts in your inventory, use the ping
module:
host1 | SUCCESS => { "changed": false, "ping": "pong" } host2 | SUCCESS => { "changed": false, "ping": "pong" }
Run a Shell Command
To run a shell command on target hosts, use the shell
module:
host1 | SUCCESS | rc=0 >> 12:34:56 up 1:23, 2 users, load average: 0.00, 0.01, 0.05 host2 | SUCCESS | rc=0 >> 12:34:57 up 5:46, 1 user, load average: 0.00, 0.01, 0.05
Copy a File
To copy a file to target hosts, use the copy
module:
host1 | SUCCESS => { "changed": true, "dest": "/path/to/remote/file", "src": "/path/to/local/file" } host2 | SUCCESS => { "changed": true, "dest": "/path/to/remote/file", "src": "/path/to/local/file" }
Using Patterns
Patterns allow you to specify which hosts or groups of hosts to run the ad-hoc command against. Some examples of patterns include:
all
: Run the command on all hosts.webservers
: Run the command on hosts in the "webservers" group.host1
: Run the command on a specific host named "host1".host1:host2
: Run the command on multiple specific hosts.
For example, to run a ping command only on the "webservers" group:
Conclusion
Ansible ad-hoc commands are a powerful way to quickly execute tasks across multiple machines without the need for a playbook. By mastering the use of ad-hoc commands, you can perform efficient and targeted operations on your infrastructure. We hope this tutorial has provided you with a comprehensive understanding of running Ansible ad-hoc commands.