首页 > 解决方案 > 如何指定要在 Ansible 剧本中使用的 Python 版本?

问题描述

我正在开发一个仍在运行 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

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

- hosts: test_server
    ansible_python_interpreter: /usr/bin/python

- hosts: test_server
  tasks:
    - name: install pip
      ansible_python_interpreter: /usr/bin/python
      apt:
        name: python-pip

但ansible抱怨说

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

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

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

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

标签: ansible

解决方案


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

- hosts: test_server
  tasks:
    - name: install pip
      ansible_python_interpreter: /usr/bin/python
      apt:
        name: python-pip

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


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

- hosts: test_server
  tasks:
    - name: install pip
      apt:
        name: python-pip
      vars:
        ansible_python_interpreter: /usr/bin/python

,或者在剧本的范围内

- hosts: test_server
  vars:
    ansible_python_interpreter: /usr/bin/python
  tasks:
    - name: install pip
      apt:
        name: python-pip

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



推荐阅读