Executing Commands Across Multiple Hosts
One of the primary benefits of Ansible ad-hoc commands is the ability to execute tasks on multiple hosts simultaneously. This section will guide you through the process of executing commands across multiple hosts using Ansible.
Executing Ad-Hoc Commands
To execute an ad-hoc command on multiple hosts, you can use the ansible
command followed by the host pattern and the module you want to run. The basic syntax is:
ansible <host_pattern> -m <module_name> -a "<module_arguments>"
Here's an example of how to check the uptime of all hosts in the "webservers" group:
ansible webservers -m command -a "uptime"
In this example, webservers
is the host pattern, command
is the module used to execute a command, and "uptime"
is the argument passed to the module.
Targeting Hosts
You can target hosts in your inventory using various host patterns. Some common patterns include:
all
: Targets all hosts in the inventory
webservers
: Targets hosts in the "webservers" group
app[01:05]
: Targets hosts named "app01" through "app05"
app*.example.com
: Targets hosts that match the wildcard pattern
Modules and Arguments
Ansible provides a wide range of modules that you can use to perform various tasks. Some commonly used modules include:
command
: Executes a command on the remote host
shell
: Executes a shell command on the remote host
file
: Manages the state of a file or directory
package
: Manages packages on the remote host
You can pass arguments to these modules using the -a
option. For example, to install the nginx
package on all hosts in the "webservers" group:
ansible webservers -m package -a "name=nginx state=present"
Gathering Facts
Ansible also provides a setup
module that you can use to gather information about the remote hosts, such as operating system, CPU, memory, and more. This information can be useful when writing more complex ad-hoc commands or playbooks. To gather facts about all hosts in the inventory:
ansible all -m setup
By understanding how to execute ad-hoc commands across multiple hosts, you can quickly and efficiently perform a wide range of tasks on your infrastructure. Let's now explore some practical use cases for Ansible ad-hoc commands.