Executing Commands on Remote Hosts
Basic Command Execution
To execute a command on a remote host using the Ansible Command module, you can use the following basic syntax:
- name: Execute a command on remote host
command: <command>
register: <result_variable>
become: yes
In this example, <command>
is the actual command you want to execute on the remote host, and <result_variable>
is the variable that will store the output of the command. The become
parameter is set to yes
to run the command with elevated privileges (if required).
For example, to check the uptime of a remote host:
- name: Check uptime of remote host
command: uptime
register: uptime_result
become: yes
The output of the uptime
command will be stored in the uptime_result
variable, which you can then use in your playbook or ad-hoc command.
Handling Command Errors
By default, the Ansible Command module will fail if the executed command returns a non-zero exit code. You can handle command errors by using the ignore_errors
parameter:
- name: Execute a command on remote host
command: <command>
register: <result_variable>
ignore_errors: yes
This will allow the playbook to continue executing even if the command fails.
Capturing Command Output
You can capture the output of a command by using the register
parameter, as shown in the previous examples. The output will be stored in the specified variable, which you can then use in your playbook or ad-hoc command.
For example, to capture the output of the uptime
command and print it:
- name: Check uptime of remote host
command: uptime
register: uptime_result
become: yes
- name: Print uptime
debug:
msg: "{{ uptime_result.stdout }}"
This will print the output of the uptime
command to the console.
By understanding the basics of executing commands on remote hosts with the Ansible Command module, you can effectively automate a wide range of tasks in your infrastructure.