bashansible

Ansible, copy script, then execute in remote machine


I want to copy a script to a remote server and then execute it. I can copy it to the directory /home/user/scripts, but when I run ansible script, it returns Could not find or access '/home/user/scripts/servicios.sh'

The full error output is:

fatal: [192.168.1.142]: FAILED! => {"changed": false, "msg": "Could not find or access '/home/user/scripts/servicios.sh'"}

Here is the ansible playbook

- name: correr script
 hosts: all
 tasks:
         - name: crear carpeta de scripts
           file:
                   path: /home/user/scripts
                   state: directory

         - name: copiar el script
           copy:
                   src: /home/local/servicios.sh
                   dest: /home/user/scripts/servicios.sh

         - name: ejecutar script como sudo
           become: yes
           script: /home/user/scripts/servicios.sh 




Solution

  • You don’t need to create a directory and copy the script to target (remote node), the script module does that for you. It takes the script name followed by a list of space-delimited arguments. The local script at path will be transferred to the remote node and then executed. The script will be processed through the shell environment on the remote node. You were getting the error because script module expects the path /home/user/scripts/servicios.sh on your Ansible controller (the node where you are running the playbook from). To make it work you can specify correct path (/home/local/servicios.sh) in script task instead of /home/user/scripts/servicios.sh which is the path on the remote node. So you can change the playbook like this: You can also register the result of that command as a variable if you would like to see that.

    ---
    - name: correr script
      hosts: all
      become: yes
      tasks:
        - name: ejecutar script como sudo
          script: /home/local/servicios.sh
          register: console
    
        - debug: msg="{{ console.stdout }}"
    
        - debug: msg="{{ console.stderr }}" 
    

    What if don’t want to go for script module and you are interested in creating a directory and copy the script to target (remote node) explicitly, and run it? No worries, you can still use the command module like this:

    ---
    - name: correr script
      hosts: all
      become: yes
      tasks:
        - name: crear carpeta de scripts
          file:
            path: /home/user/scripts
            state: directory
    
        - name: copiar el script
          copy:
            src: /home/local/servicios.sh
            dest: /home/user/scripts/servicios.sh
    
        - name: ejecutar script como sudo
          command: bash /home/user/scripts/servicios.sh
          register: console
    
        - debug: msg="{{ console.stdout }}"
    
        - debug: msg="{{ console.stderr }}" 
    

    But I strongly recommend to go for script module.