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

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.

This question is related to shell ansible remote-server

The answer is


It's better to use script module for that:
http://docs.ansible.com/script_module.html


You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

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

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to ansible

Specifying ssh key in ansible playbook file Ansible: how to get output to display How to do multiline shell script in Ansible Accessing inventory host variable in Ansible playbook Ansible: get current target host's IP address Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors Ansible: How to delete files and folders inside a directory? How to pass a user / password in ansible command How to test that a registered variable is not empty? Copy multiple files with Ansible

Examples related to remote-server

How to open remote files in sublime text 3 How to execute a shell script on a remote server using Ansible? How to connect to a remote Windows machine to execute commands using python? How do I push a local Git branch to master branch in the remote? Connecting to remote MySQL server using PHP Connect to external server by using phpMyAdmin Remove a file from a Git repository without deleting it from the local filesystem