Execute bash script on remote host

158 Views Asked by At

I write playbook Copy my bash script to remote host & run it, but on second task i have problem:

TASK [Activate bash script] *****************************************************************************************************************
fatal: [hostname]: FAILED! => {"changed": false, "msg": "Could not find or access 'sh'\nSearched in:\n\t/home/ansible/ansible/playbooks/files/sh\n\t/home/ansible/ansible/playbooks/sh\n\t/home/ansible/ansible/playbooks/files/sh\n\t/home/ansible/ansible/playbooks/sh on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"}

My playbook:

---
- name: install sh script - db cleaner
  hosts: all
  vars:
    ansible_become_user: root
    ansible_become_password: password
    ansible_become_method: sudo
  gather_facts: false
  tasks:
  - name: Install bash script
    raw: wget "http://ip/clear_db_duplo.sh" -O /mnt/azimuth-data/temp/clear_db_duplo.sh && chmod +x /mnt/azimuth-data/temp/clear_db_duplo.sh

  - name: Activate bash script
    become: yes
    script: sh /mnt/azimuth-data/temp/clear_db_duplo.sh

On local use after copy this script are executed

try to use

command:
script:
raw:
2

There are 2 best solutions below

1
user000001 On

I believe you want:

  tasks:
  - name: Download bash script
    command: wget "http://ip/clear_db_duplo.sh" -O /mnt/azimuth-data/temp/clear_db_duplo.sh 

  - name: Set permissions
    command: chmod +x /mnt/azimuth-data/temp/clear_db_duplo.sh

  - name: Activate bash script
    become: yes
    command: /mnt/azimuth-data/temp/clear_db_duplo.sh
0
U880D On

In order to download files from HTTP, HTTPS, or FTP to node, use get_url module.

---
- name: Install sh script - db cleaner
  hosts: all
  become: trrue
  gather_facts: false

  vars:

    IP: 192.0.2.1
    SCRIPT: clear_db_duplo.sh

  tasks:

  - name: Install script
    ansible.builtin.get_url:
      url: "http://{{ IP }}/{{ SCRIPT }}"
      dest: /mnt/azimuth-data/temp/
      mode: '0700'

Please take note that script module – Runs a local script on a Remote Node after transferring it from the Control Node. Therefore the whole case could probably done in a single script task, if the the script becomes provided on the Control Nodes project file directory. See in example How to convert a curl | bash command line into an Ansible playbook?