如何使用Ansible在远程服务器上执行shell脚本?

如何使用Ansible在远程服务器上执行shell脚本?,shell,ansible,remote-server,Shell,Ansible,Remote Server,我计划使用Ansible playbook在远程服务器上执行shell脚本 空白test.sh文件: touch test.sh 剧本: --- - 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 mod

我计划使用Ansible playbook在远程服务器上执行shell脚本

空白test.sh文件:

touch test.sh
剧本:

---
- 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

当我运行playbook时,传输成功,但脚本未执行。

local\u action
在本地服务器上运行命令,而不是在
hosts
参数中指定的服务器上运行命令

将“执行脚本”任务更改为

它应该做到这一点

您不需要在命令行中重复sudo,因为您已经在playbook中定义了它

根据Ansible 1.4中的
user
参数被重命名为
remote\u user
,因此您也应该对其进行更改

remote_user: test_user
因此,剧本将成为:

---
- 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

最好使用
脚本
模块:

您可以使用模块

范例

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

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

您可以使用模板模块将本地计算机上是否存在脚本复制到远程计算机并执行它

 - 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
-名称:将脚本从本地复制到远程计算机
主机:远程计算机
任务:
-名称:将脚本复制到远程计算机
模板:src=script.sh.2 dest=/script.sh mode=755
-名称:在远程计算机上执行脚本
脚本:sh/script.sh

模块不是这样做的吗?您能解释一下原因吗?它将复制操作和在远程主机上运行脚本结合在一起。例外情况是,如果脚本是模板文件(例如,在播放过程中,您可以使用Ansible变量在脚本中动态填充占位符)。在这种情况下,您将使用
模板
后跟
命令sh..
@343\u infence\u Spark关于您上面提到的语句,请您给出一个脚本被定义为模板的示例file@ambikanair-内联格式在重播中很困难,检查一下要点:脚本不允许异步。为什么这是被否决的,这应该是正确的答案,而不是使用shell模块。可能是因为它用于复制和运行本地脚本,而不仅仅是在服务器上运行脚本?如果脚本在线怎么办?我可以运行wget吗?IE(脚本:wget-qO deployll.sh&&bash deployll.sh)Tobb:脚本一步复制并导出脚本。路径与执行ansible的主机相对。这是一个正确答案,在ansible中不是最佳做法,最好使用脚本模块,而不是使用copy和shell/command。如果需要在文件中更改变量,可以使用template和shell/command。我在EC2实例上的脚本模块也有问题。这种方法有效me@JonasLibbrecht脚本模块可能有用,但copy+命令仍然是明智的选择。甚至脚本模块的文档也给出了复制+命令更好的示例“如果您依赖于分离的stdout和stderr结果键,请切换到复制+命令任务集,而不是使用脚本。”我发现脚本有问题的另一个例子是,在Vagrant上使用Linux时,Windows主机-脚本模块无法执行带有从Windows GIT克隆的Windows结束行字符的python/bash文件。如果在执行脚本时需要使用运行时参数,并希望在yml文件中指定这些参数,该怎么办?比方说,我想运行一个测试服务状态的脚本,参数是服务名称:
checkservicestash-splunk
。我怎样才能做到这一点?
 - 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