如何指定要在 Ansible 剧本中使用的 Python 版本?

Chr*_*vey 6 ansible

我正在处理一个仍在运行 Python 2 的项目。我正在尝试使用 Ansible 来设置新的测试服务器。我开始使用的基本 Linux 安装只有 Python 3,所以我需要我的第一个“引导程序”剧本来使用 Python 3,但随后我希望后续剧本使用 Python 2。

我可以在我的清单文件中指定 python 的版本,如下所示:

[test_server:vars]
ansible_python_interpreter=/usr/bin/python3

[test_server]
test_server.example.com
Run Code Online (Sandbox Code Playgroud)

但随后我必须编辑清单文件以确保我使用 Python 3 作为引导剧本,然后再次为我的其余剧本编辑它。这似乎很奇怪。我ansible_python_interpreter在我的剧本中尝试了几个不同版本的更改,例如

- hosts: test_server
    ansible_python_interpreter: /usr/bin/python
Run Code Online (Sandbox Code Playgroud)

- hosts: test_server
  tasks:
    - name: install pip
      ansible_python_interpreter: /usr/bin/python
      apt:
        name: python-pip
Run Code Online (Sandbox Code Playgroud)

但 ansible 抱怨说

错误!“ansible_python_interpreter”不是任务的有效属性

即使https://docs.ansible.com/ansible/latest/reference_appendices/interpreter_discovery.html

您仍然可以将 ansible_python_interpreter 设置为任何变量级别的特定路径(例如,在 host_vars、vars 文件、剧本等)。

正确执行此操作的调用是什么?

Vla*_*tka 7

问:正确执行此操作的调用是什么?

- hosts: test_server
  tasks:
    - name: install pip
      ansible_python_interpreter: /usr/bin/python
      apt:
        name: python-pip
Run Code Online (Sandbox Code Playgroud)

错误!“ansible_python_interpreter”不是任务的有效属性


A: ansible_python_interpreter不是剧本关键字。它是一个变量,必须如此声明。例如在任务范围内

- hosts: test_server
  tasks:
    - name: install pip
      apt:
        name: python-pip
      vars:
        ansible_python_interpreter: /usr/bin/python
Run Code Online (Sandbox Code Playgroud)

,或在剧本的范围内

- hosts: test_server
  vars:
    ansible_python_interpreter: /usr/bin/python
  tasks:
    - name: install pip
      apt:
        name: python-pip
Run Code Online (Sandbox Code Playgroud)

,或在任何其他合适的地方。请参阅变量优先级:我应该将变量放在哪里?