Ansible - 如何在 SSH 会话中设置 ansible_env.PATH

Ansible - how ansible_env.PATH is set in SSH session

我试图使用 Ansible 执行一个简单的 python --version 命令,但无论我如何尝试它都无法正常工作:通过 shell 模块,通过 command 模块,通过 script 模块,通过 playbook 或 ad-hoc。

我总是收到错误消息:

unknown option

例如剧本:

---

- name: testing
  hosts: myhost
  sudo: False

  tasks:
       - name: python version
         shell: python --version

然后我意识到这是由于 Ansible 如何在 SSH 会话中加载环境。实际上错误不是来自 Ansible 或命令解析,而是来自 Python 版本 2.4,它以某种方式进入 PATH (/usr/local/bin).

似乎 Python 2.4 不知道 --version 标志。

最有趣的部分是,当我与 Ansible 的同一用户对同一主机执行 SSH 时,我得到的 PATH 元素顺序正确,第一个位置 Python exists 是正确的 Python 3,而 /usr/local/bin 深埋在 PATH.

但是当我在 playbook 中添加一个 which python 任务时,我看到 Ansible 从 /usr/local/bin 解析了 Python,这是旧的 (v2.4)

当我执行 ansible myhost -m setup 时,我可以看到 ansible_env.PATH 变量比我通过直接登录获得的 PATH 变量短得多。

如果能了解其设置规则,那就太好了。

这里问了完全相同的问题:

http://grokbase.com/t/gg/ansible-project/1479n0d0qp/ansible-env-path-how-is-it-set

但一直没有确定的答案。

  • 要获取执行模块的 python 版本和 ansible 本身,您应该使用 ansible_fact ansible_python_version
  • (我的自制推荐)使用 command 模块时使用完整路径。

so the correct answer for me was: in inventory file set the ansible_python_interpreter=/path/to/correct/python and then it will be able to use the indicated python when logging to the remote and obviously find it in the PATH.

这不是真的。 - shell: python --version 不会使用 ansible_python_interpreter。它只是通过在 PATH 中查找可执行文件(如果它不是绝对路径)来执行你给它的任何命令。

例如如果

  • 您已经设置了启动文件(/etc/profile/etc/profile.d/*.*rc 等),因此 python 2.4 在 PATH 中排在第一位,并且
  • 您将 ansible_python_interpreter 设置为 /path/to/python3 my_host

然后:

- hosts: my_host
  tasks:
    - debug: msg="{{ansible_python_interpreter}}"      # would print /path/to/python3
    - debug: msg="{{ansible_python_version}}"          # would print 3.x
    - shell: python -c 'import sys; print sys.version' # would execute python 2.4
      register: py_version
    - debug: msg="{{py_version}}"                      # would print 2.4

您应该做的是以下其中一项:

  • 正确设置路径。 (这不是一个真正的选择,因为 "how ansible sets PATH" 未定义,请参阅下面 Eugene 的评论)
  • command 模块(或 shell 模块)使用绝对路径。