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

Pat*_*ttu 48 shell remote-server ansible ansible-playbook

我打算使用Ansible playbook在远程服务器上执行shell脚本.

test.sh:

touch test.txt
Run Code Online (Sandbox Code Playgroud)

剧本:

---
- 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
Run Code Online (Sandbox Code Playgroud)

当我运行playbook时,传输成功,但脚本没有执行.

小智 89

你可以使用脚本模块

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

     - name: Copy and Execute the script 
       script: /home/user/userScript.sh
Run Code Online (Sandbox Code Playgroud)

  • 这不是问题所问的;脚本模块运行 ansible 控制器本地的脚本。远程机器有脚本文件。 (11认同)
  • 为什么这是downvoted,这应该是正确答案而不是使用shell模块. (6认同)
  • 也许是因为它是用于复制和运行本地脚本,而不仅仅是在服务器上运行脚本? (4认同)

Pas*_*i H 43

local_action在本地服务器上运行该命令,而不是在hosts参数中指定的服务器上运行.

将"执行脚本"任务更改为

- name: Execute the script
  command: sh /home/test_user/test.sh
Run Code Online (Sandbox Code Playgroud)

它应该这样做.

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

根据Ansible Intro to Playbooks user参数remote_user在Ansible 1.4中重命名,所以你也应该改变它

remote_user: test_user
Run Code Online (Sandbox Code Playgroud)

所以,剧本将成为:

---
- 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
Run Code Online (Sandbox Code Playgroud)

  • @JonasLibbrecht脚本模块可能很有用,但复制+命令仍然是明智的选择.即使是脚本模块的文档也提供了复制+命令更好的示例"如果您依赖于分离的stdout和stderr结果键,请切换到复制+命令集任务而不是使用脚本." 我发现脚本问题的其他情况是使用具有Windows主机的Vagrant上的Linux - 脚本模块无法在Windows上从GIT克隆的Windows终止行字符执行python/bash文件. (4认同)
  • 到目前为止,这是一个正确的答案,而不是 Ansible 中的最佳实践,最好使用脚本模块,而不是使用复制和 shell/命令。 (2认同)
  • 如果需要在文件中更改变量,可以使用模板和 shell/命令。我在 EC2 实例上的脚本模块上也遇到了问题。这个方法对我有用 (2认同)

vor*_*nin 21

最好使用script模块:http:
//docs.ansible.com/script_module.html

  • 它结合了复制操作和在远程主机上运行脚本.例外情况是脚本是模板文件(例如,在播放过程中,您在脚本中使用Ansible变量动态填充占位符).在这种情况下,您将使用`template`后跟`command sh ...` (7认同)
  • 你能解释为什么吗? (2认同)
  • @ambikanair - 内联格式很难重播,请查看这个要点:https://gist.github.com/duntonr/b0f02efcc9c780ca73a7 (2认同)

fan*_*ing 8

对于想要临时命令的人

ansible group_or_hostname -m script -a "/home/user/userScript.sh"
Run Code Online (Sandbox Code Playgroud)

或使用相对路径

ansible group_or_hostname -m script -a "userScript.sh"
Run Code Online (Sandbox Code Playgroud)