Running Scripts on Remote Hosts
One of the most common use cases for Ansible is executing scripts on remote hosts. This can be useful for a variety of tasks, such as running system maintenance scripts, deploying applications, or performing ad-hoc troubleshooting.
To run a script on a remote host using Ansible, you can use the script
module. This module allows you to copy a local script to the remote host and execute it.
Here's an example of how to use the script
module:
- hosts: webservers
tasks:
- name: Run a script on remote hosts
script: /path/to/script.sh
In this example, the script.sh
file is located on the Ansible control node, and it will be copied to and executed on all the hosts in the "webservers" group.
You can also pass arguments to the script using the args
parameter:
- hosts: webservers
tasks:
- name: Run a script with arguments
script: /path/to/script.sh
args:
- arg1
- arg2
In this case, the script will be executed with the arguments arg1
and arg2
.
If you need to capture the output of the script, you can use the register
keyword to store the output in a variable:
- hosts: webservers
tasks:
- name: Run a script and capture output
script: /path/to/script.sh
register: script_output
- name: Print script output
debug:
var: script_output.stdout
In this example, the output of the script is stored in the script_output.stdout
variable, which can then be printed or used in subsequent tasks.
You can also use the become
keyword to run the script with elevated privileges (e.g., as the root
user):
- hosts: webservers
tasks:
- name: Run a script with elevated privileges
script: /path/to/script.sh
become: true
This will execute the script with sudo
on the remote hosts.
By using the script
module, you can easily execute scripts on remote hosts, making it a powerful tool for automating a wide range of tasks with LabEx.