升级Python和Ansible后执行Playbook报错/bin/env python不存在
解决Ansible-playbook执行报错“/bin/sh: /bin/env python: No such file or directory”
问题概述
升级Python(3.12.11)和Ansible(core 2.18.8)后,执行ansible-playbook时出现如下错误:
[2025-08-12T08:21:59.996Z] fatal: [host]: FAILED! => {"changed": false, "module_stderr": "Shared connection to host closed.\r\n", "module_stdout": "/bin/sh: /bin/env python: No such file or directory\r\n", "msg": "The module failed to execute correctly, you probably need to set the interpreter.\nSee stdout/stderr for the exact error", "rc": 127}
但通过SSH直接执行/bin/env python --version、使用Ansible临时shell命令执行该命令均能正常返回Python版本;将/bin/env python替换为/usr/local/bin/python完整路径后,Ansible可正常执行。
环境信息
- Python版本:
# python --version Python 3.12.11 - Ansible版本:
# ansible --version ansible [core 2.18.8] config file = None configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.12/site-packages/ansible ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/bin/ansible python version = 3.12.11 (main, Jun 19 2025, 11:41:33) [GCC 8.5.0 20210514 (Red Hat 8.5.0-27)] (/usr/bin/python3.12) jinja version = 3.1.6 libyaml = True
排查验证
- SSH远程执行命令正常:
$ ssh host " /bin/env python --version" Python 3.12.11 - Ansible临时shell命令执行正常:
$ ansible localhost -u user -m shell -a "/bin/env python --version" [WARNING]: No inventory was parsed, only implicit localhost is available localhost | CHANGED | rc=0 >> Python 3.12.11
解决方案
1. 全局配置Python解释器
创建或修改ansible.cfg文件(默认路径为/etc/ansible/ansible.cfg或当前目录下的ansible.cfg),添加以下配置:
[defaults] interpreter_python = /usr/local/bin/python
也可通过环境变量临时设置:
export ANSIBLE_PYTHON_INTERPRETER=/usr/local/bin/python
2. 在Playbook中指定解释器
在Playbook的主机块中直接定义变量:
- name: 示例任务 hosts: host vars: ansible_python_interpreter: /usr/local/bin/python tasks: # 此处添加你的任务
3. 在Inventory文件中指定
在Inventory文件里为目标主机绑定解释器路径:
host ansible_python_interpreter=/usr/local/bin/python
4. 创建软链接(需谨慎)
如果系统允许,在目标主机上创建python命令的软链接,让/bin/env能找到它:
ln -s /usr/local/bin/python /usr/bin/python
注意:若系统原有Python2环境,此操作可能影响依赖Python2的程序,需提前评估风险。
问题原因
Ansible模块执行时的运行环境与SSH登录环境、临时shell模块环境存在差异:模块执行时的PATH环境变量可能未包含Python所在目录,导致/bin/env无法找到python命令;而SSH登录和临时shell命令会加载用户的环境配置(如.bashrc、.profile),PATH包含了Python路径,因此可正常执行。
内容的提问来源于stack exchange,提问作者pmann
相关产品推荐
相关产品推荐

