Ansible Ad-Hoc Commands
Introduction
Ansible Ad-Hoc commands are one-off commands that allow users to perform a specific task on a number of managed nodes without needing to write a playbook. They are useful for quick tasks such as installing packages, copying files, or restarting services.
Key Concepts
- Inventory: A file specifying the hosts on which commands will be executed.
- Module: A tool to perform a specific task (e.g.,
yum
,copy
,service
). - Ad-Hoc Commands: Simple commands executed directly on the command line.
Usage of Ad-Hoc Commands
Ad-Hoc commands can be executed using the following syntax:
ansible <host-pattern> -m <module-name> -a "<module-arguments>"
Where:
- <host-pattern>: Specifies the group of hosts or individual hosts.
- <module-name>: The Ansible module you want to use.
- <module-arguments>: The arguments specific to the module.
Examples
Example 1: Ping All Hosts
ansible all -m ping
This command checks if all hosts in the inventory can be reached.
Example 2: Install a Package
ansible webservers -m yum -a "name=httpd state=present"
This installs the httpd
package on all hosts in the webservers
group.
Example 3: Restart a Service
ansible dbservers -m service -a "name=mysqld state=restarted"
This command restarts the mysqld
service on all hosts in the dbservers
group.
Best Practices
- Always use the correct host pattern to avoid unintended executions.
- Test commands on a single host before applying them to multiple hosts.
- Keep your inventory up to date for effective management.
FAQ
What are Ansible Ad-Hoc commands?
They are one-time commands executed directly to manage remote systems without the need for playbooks.
Can I use Ad-Hoc commands for complex tasks?
For complex tasks involving multiple steps, it is recommended to use playbooks instead.
How do I check if a host is reachable?
You can use the ping
module in an Ad-Hoc command: ansible all -m ping
.