如何使用 Ansible 在远程服务器上执行 shell 脚本? [英] How to execute a shell script on a remote server using Ansible?

查看:31
本文介绍了如何使用 Ansible 在远程服务器上执行 shell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

空白的 test.sh 文件:

blank test.sh file:

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

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

When I run the playbook, the transfer successfully occurs but the script is not executed.

推荐答案

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

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

它应该这样做.

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

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

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

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

所以,剧本将变成:

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

这篇关于如何使用 Ansible 在远程服务器上执行 shell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆