Executing Remote Shell Commands
Executing Ad-Hoc Commands
Ansible allows you to execute ad-hoc commands on remote hosts without the need to create a Playbook. This is useful for quick, one-time tasks or for testing purposes. To execute an ad-hoc command, you can use the ansible
command-line tool with the following syntax:
ansible <host_pattern> -m <module> -a "<module_arguments>"
For example, to execute the uptime
command on all hosts in the webservers
group, you can use the following command:
ansible webservers -m command -a "uptime"
Using the command
Module
The command
module is one of the most commonly used modules for executing remote shell commands in Ansible. It allows you to run arbitrary commands on the target hosts. Here's an example Playbook that uses the command
module:
- hosts: webservers
tasks:
- name: Run a simple command
command: echo "Hello, LabEx!"
register: command_output
- name: Display command output
debug:
var: command_output.stdout
In this example, the command
module is used to execute the echo "Hello, LabEx!"
command on the webservers
group. The output of the command is stored in the command_output
variable, which is then displayed using the debug
module.
Handling Command Errors
By default, Ansible will fail the task if the remote command returns a non-zero exit code. You can handle command errors by using the ignore_errors
option or by checking the rc
(return code) variable in your Playbook. Here's an example:
- hosts: webservers
tasks:
- name: Run a command that might fail
command: /path/to/command_that_might_fail
register: command_result
ignore_errors: yes
- name: Check command result
debug:
msg: "Command failed with return code {{ command_result.rc }}"
when: command_result.rc != 0
In this example, the ignore_errors
option is used to prevent the task from failing if the remote command returns a non-zero exit code. The rc
variable is then checked to determine the return code of the command, and a debug message is displayed if the command failed.