Ansible Playbook执行远程bash脚本失败:找不到sh命令求助
问题分析与解决
错误根源
你用错了script模块的用法:script模块的作用是将Ansible控制器本地的脚本文件上传到远程主机后执行,而你写的script: sh /mnt/azimuth-data/temp/clear_db_duplo.sh,会让Ansible误以为要在控制器本地找名为sh的文件,所以才会在控制器的playbooks目录下搜索,导致报错。
修正方案
直接改用shell或command模块执行远程主机上已存在的脚本:
方案1:使用shell模块(推荐)
shell模块支持shell环境的特性(如shebang解析、管道等),适合执行已在远程的脚本:
- name: Activate bash script become: yes shell: /mnt/azimuth-data/temp/clear_db_duplo.sh
如果脚本没有添加#!/bin/bash的shebang行,可以显式指定bash执行:
- name: Activate bash script become: yes shell: bash /mnt/azimuth-data/temp/clear_db_duplo.sh
方案2:使用command模块
如果脚本不需要shell特性,也可以用command模块,注意需要指定完整路径或确保脚本在PATH中:
- name: Activate bash script become: yes command: /mnt/azimuth-data/temp/clear_db_duplo.sh
额外优化建议
第一个任务用raw模块不够规范,建议改用Ansible官方的get_url模块,它支持文件校验、重试、权限设置等功能,更可靠:
- name: Download and set permissions for bash script become: yes get_url: url: "http://ip/clear_db_duplo.sh" dest: /mnt/azimuth-data/temp/clear_db_duplo.sh mode: '0755' # 直接设置可执行权限,无需单独chmod
内容的提问来源于stack exchange,提问作者December EveryDay
相关产品推荐
相关产品推荐

