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

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

问题描述

我计划使用Ansible剧本在远程服务器上执行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 Playbooks简介 user参数在Ansible中重命名为remote_user 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天全站免登陆