How to execute a script on a remote host with Ansible

AnsibleAnsibleBeginner
Practice Now

Introduction

Ansible is a powerful IT automation tool that simplifies the process of executing scripts on remote hosts. In this tutorial, we will explore how to leverage Ansible to run scripts on remote servers, covering practical use cases and the benefits of this approach.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ansible(("`Ansible`")) -.-> ansible/PlaybookEssentialsGroup(["`Playbook Essentials`"]) ansible(("`Ansible`")) -.-> ansible/ModuleOperationsGroup(["`Module Operations`"]) ansible/PlaybookEssentialsGroup -.-> ansible/playbook("`Execute Playbook`") ansible/PlaybookEssentialsGroup -.-> ansible/with_items("`Iterate Items`") ansible/PlaybookEssentialsGroup -.-> ansible/roles("`Assign Roles`") ansible/PlaybookEssentialsGroup -.-> ansible/loop("`Iteration`") ansible/ModuleOperationsGroup -.-> ansible/command("`Execute Commands`") subgraph Lab Skills ansible/playbook -.-> lab-414953{{"`How to execute a script on a remote host with Ansible`"}} ansible/with_items -.-> lab-414953{{"`How to execute a script on a remote host with Ansible`"}} ansible/roles -.-> lab-414953{{"`How to execute a script on a remote host with Ansible`"}} ansible/loop -.-> lab-414953{{"`How to execute a script on a remote host with Ansible`"}} ansible/command -.-> lab-414953{{"`How to execute a script on a remote host with Ansible`"}} end

Introducing Ansible

Ansible is an open-source software provisioning, configuration management, and application-deployment tool. It is designed to be simple to use, yet powerful enough to manage complex IT environments. Ansible works by connecting to your nodes (remote systems) and pushing out small programs called "Ansible modules" to those nodes. These modules then execute on the remote nodes and return the results back to the Ansible control node.

One of the key benefits of Ansible is its agentless architecture. Ansible does not require any special software to be installed on the remote nodes, which makes it easy to deploy and manage. Instead, Ansible uses SSH (or Windows Remote Management) to communicate with the remote systems.

Ansible can be used to automate a wide range of tasks, including:

  • System Provisioning: Deploying and configuring new servers, virtual machines, or containers.
  • Configuration Management: Ensuring that systems are configured correctly and consistently.
  • Application Deployment: Deploying and updating applications across multiple systems.
  • Task Automation: Automating repetitive tasks, such as backups, updates, or monitoring.

To get started with Ansible, you'll need to have a control node (the system from which you'll run Ansible commands) and one or more remote nodes (the systems you want to manage). On the control node, you'll need to install Ansible and create an inventory file that defines the remote nodes you want to manage.

Here's an example of an Ansible inventory file:

[webservers]
web01 ansible_host=192.168.1.100
web02 ansible_host=192.168.1.101

[databases]
db01 ansible_host=192.168.1.200
db02 ansible_host=192.168.1.201

This inventory file defines two groups of hosts: "webservers" and "databases". Each host has an ansible_host variable that specifies its IP address or hostname.

With the inventory file in place, you can start running Ansible commands to manage your systems. For example, to run a simple command on all the webservers, you can use the following command:

ansible webservers -m shell -a "uptime"

This command will execute the uptime command on all the hosts in the "webservers" group and display the results.

In the next section, we'll explore how to use Ansible to execute scripts on remote hosts.

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.

Practical Use Cases

Ansible's ability to execute scripts on remote hosts can be applied to a wide range of practical use cases. Here are a few examples:

System Maintenance and Troubleshooting

Imagine you have a fleet of web servers that require regular maintenance, such as log rotation, software updates, or performance tuning. You can create a script that performs these tasks and use Ansible to execute the script on all the servers in your inventory. This ensures that the maintenance is performed consistently and efficiently across your infrastructure.

- hosts: webservers
  tasks:
    - name: Run maintenance script
      script: /path/to/maintenance_script.sh

Application Deployment

When deploying a new version of your application, you may need to run a series of tasks on the target servers, such as stopping the existing service, copying the new code, running database migrations, and starting the new service. You can encapsulate all of these steps into a single script and use Ansible to execute it on the relevant hosts.

- hosts: app_servers
  tasks:
    - name: Deploy new application version
      script: /path/to/deploy_script.sh

Incident Response and Remediation

During an incident, you may need to quickly gather information or perform remediation steps on affected systems. By having a set of pre-written scripts, you can use Ansible to execute these scripts on the relevant hosts, streamlining your incident response process.

- hosts: affected_hosts
  tasks:
    - name: Run incident response script
      script: /path/to/incident_response.sh

Configuration Management and Compliance

Ansible can be used to ensure that your systems are configured correctly and consistently. By creating scripts that apply specific configurations or check for compliance, you can use Ansible to automate these tasks and ensure that your infrastructure remains in a desired state.

- hosts: all
  tasks:
    - name: Apply security configuration
      script: /path/to/security_config.sh

By leveraging Ansible's script module, you can easily execute scripts on remote hosts, making it a powerful tool for automating a wide range of tasks and streamlining your infrastructure management with LabEx.

Summary

Ansible provides a seamless way to execute scripts on remote hosts, enabling you to automate various tasks and streamline your server management processes. By following the steps outlined in this tutorial, you can leverage Ansible's capabilities to enhance your IT operations and improve the efficiency of your remote server management.

Other Ansible Tutorials you may like