JustGeek.in Tech, simplified.

Run a shell script using ansible

So sometimes, it’s not just feasible to develop a whole playbook, Instead, you want to run a shell script using ansible on remote servers.

The best approach to achieve this would be to create a script using ansible on a remote server.

You can use the copy module in Ansible to create a file in a remote location with specific content.

Sample Script.

So above script is creating a file named remote.sh at the location /home/justgeek/remote.sh and it will use the copy module to add your shell script.

In the same ansible-playbook, you can run that shell script using the shell module. You can add the following run the shell script.

    - name: Run Shell Script.
      shell: sh /home/justgeek/remote.sh

After the shell script has been executed, ansible won’t do anything but it’s always better to clean up things. It’s a good idea to remove that shell script after you have run it.

Add the below code to your ansible-playbook to remove the script after it has run successfully.

    - name: Remove Shell Script
      file:
       path: /home/justgeek/remote.sh
       state: absent

Now, this would be what the final script would look like. The script below will do the following

  • Create a file called remote.sh on destination server with the shell script you specify
  • Run the shell script.
  • Remove the shell script from the destination server.
---
  - hosts: webapp
    gather_facts: False

    tasks:
    - name: Copy & Create File.
      copy:
       dest: /home/justgeek/remote.sh
       content: |
       #!/bin/bash
       Please place your Shell Script here.

    - name: Run Shell Script.
      shell: sh /home/justgeek/remote.sh

    - name: Remove Shell Script
      file:
       path: /home/justgeek/remote.sh
       state: absent

Here, we are putting the shell script in the ansible-playbook and then we are running it on the remote server, another way is to create a script file on the ansible server and then copy the whole file to the remote server and run it using the shell module.