Table of contents
Ansible is a powerful automation tool that simplifies IT infrastructure management, configuration management, and application deployment across different environments. While Ansible's strength lies in its ability to execute complex playbooks, it also offers a convenient way to perform quick tasks using ad-hoc commands. In this blog post, we'll explore Ansible ad-hoc commands and how they can streamline your workflow.
📑What are Ansible Ad-Hoc Commands?
Ansible ad-hoc commands are simple, one-liner commands that allow you to perform tasks on remote hosts without creating a playbook. These commands are ideal for quick operations, such as restarting a service, copying a file, or gathering system information. Ad-hoc commands are executed in a single line and do not require the creation of a separate playbook file.
✅Basic Syntax
The basic syntax for Ansible ad-hoc commands is as follows:
ansible [pattern] -m [module] -a "[module options]"
pattern
: Specifies the hosts or groups of hosts you want to target. You can use patterns likeall
,webservers
, orhost1,host2
.-m
or--module-name
: Specifies the Ansible module you want to use.-a
or--args
: Specifies the arguments or options for the module.
Common Ad-Hoc Command Examples Here are some common examples of Ansible ad-hoc commands:
Ping hosts
ansible all -m ping
This command uses the
ping
module to check if the specified hosts are reachable.Restart a service
ansible webservers -m service -a "name=apache2 state=restarted"
This command restarts the Apache2 service on the hosts in the
webservers
group.Copy a file
ansible appservers -m copy -a "src=/path/to/local/file dest=/path/on/remote/host"
This command copies a local file to the specified remote hosts in the
appservers
group.Gather system information
ansible all -m setup -a "filter=ansible_distribution*"
This command retrieves distribution information from all hosts using the
setup
module and filters the output to show only the distribution-related facts.Execute a command
ansible dbservers -m command -a "uptime"
This command runs the
uptime
command on the hosts in thedbservers
group.
Ad-Hoc Commands with Privilege Escalation Some tasks may require elevated privileges (sudo) on the remote hosts. You can use the --become
or -b
option to enable privilege escalation:
ansible webservers -b --become-user=root -m service -a "name=apache2 state=restarted"
This command restarts the Apache2 service as the root
user on the webservers
hosts.
✅Conclusion
Ansible ad-hoc commands are a powerful and convenient way to perform quick tasks on remote hosts without the need for creating full-fledged playbooks. They are perfect for simple operations, troubleshooting, and gathering information. As you become more familiar with Ansible, you'll find ad-hoc commands to be an invaluable tool in your automation toolbox.
Hope you found it useful😊!