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

前端 未结 4 1419
一向
一向 2020-12-23 13:22

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

blank test.sh file:

touch test.sh

Playbook:

相关标签:
4条回答
  • 2020-12-23 13:48

    local_action runs the command on the local server, not on the servers you specify in hosts parameter.

    Change your "Execute the script" task to

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

    and it should do it.

    You don't need to repeat sudo in the command line because you have defined it already in the playbook.

    According to Ansible Intro to Playbooks user parameter was renamed to remote_user in Ansible 1.4 so you should change it, too

    remote_user: test_user
    

    So, the playbook will become:

    ---
    - name: Transfer and execute a script.
      hosts: server
      remote_user: test_user
      sudo: yes
      tasks:
         - name: Transfer the script
           copy: src=test.sh dest=/home/test_user mode=0777
    
         - name: Execute the script
           command: sh /home/test_user/test.sh
    
    0 讨论(0)
  • 2020-12-23 14:00

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

    0 讨论(0)
  • 2020-12-23 14:01

    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
    
    0 讨论(0)
  • 2020-12-23 14:04

    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
    
    0 讨论(0)
提交回复
热议问题