Executing a Simple Command with Ansible
After understanding the basics of Ansible, let's dive into executing a simple command using Ansible.
Preparing the Environment
Before we begin, ensure that you have the following prerequisites:
- Ansible installed on your control node (the machine from which you will run Ansible commands).
- An inventory file that defines the managed nodes (the machines you want to manage with Ansible).
Here's an example inventory file (inventory.txt
) with a single host:
[webservers]
192.168.1.100
Executing a Simple Command
Ansible provides the ansible
command-line tool to execute ad-hoc commands on managed nodes. To execute a simple command, such as checking the uptime of a remote host, follow these steps:
-
Open a terminal on your control node.
-
Run the following Ansible command:
ansible webservers -i inventory.txt -m shell -a "uptime"
Explanation:
ansible
: The Ansible command-line tool.
webservers
: The group of hosts defined in the inventory file.
-i inventory.txt
: The path to the inventory file.
-m shell
: The module to use, in this case, the "shell" module to execute a shell command.
-a "uptime"
: The command to execute on the remote hosts.
-
Ansible will connect to the managed nodes, execute the uptime
command, and display the output.
graph LR
A[Control Node] -- SSH --> B[Managed Node]
B -- Executes "uptime" --> C[Output]
Customizing the Command
You can customize the command to execute any other shell command on the remote hosts. For example, to list the contents of the /etc/
directory, you can use the following command:
ansible webservers -i inventory.txt -m shell -a "ls -l /etc/"
This will execute the ls -l /etc/
command on the remote hosts and display the output.
Command |
Description |
ansible |
The Ansible command-line tool. |
webservers |
The group of hosts defined in the inventory file. |
-i inventory.txt |
The path to the inventory file. |
-m shell |
The module to use, in this case, the "shell" module to execute a shell command. |
-a "uptime" |
The command to execute on the remote hosts. |
Remember, the ansible
command is useful for quickly executing one-off tasks, but for more complex and repeatable automation, you should consider using Ansible Playbooks.