How to execute a shell script on a remote server using Ansible?

Pattu picture Pattu · Jan 16, 2014 · Viewed 177.9k times · Source

I am planning to execute a shell script on a remote server using Ansible playbook.

blank test.sh file:

touch test.sh

Playbook:

---
- name: Transfer and execute a script.
  hosts: server
  user: test_user
  sudo: yes
  tasks:
     - name: Transfer the script
       copy: src=test.sh dest=/home/test_user mode=0777

     - name: Execute the script
       local_action: command sudo sh /home/test_user/test.sh

When I run the playbook, the transfer successfully occurs but the script is not executed.

Answer

Kunwar picture Kunwar · Jun 27, 2016

you can use script module

Example

- name: Transfer and execute a script.
  hosts: all
  tasks:

     - name: Copy and Execute the script 
       script: /home/user/userScript.sh