Ansible 和 Amazon Linux 2:如何使用 yum 模块 Python3?

Ansible and Amazon Linux 2: How can I use yum module with Python3?

我使用 Ansible 2.9 通过 Amazon 创建 EC2 实例 Linux 2. 出于某些目的,我需要 Python3 在 EC2 上。

所以我使用选项ansible_python_interpreter: "/usr/bin/python3"

但是有了这个选项模块 yum return 错误 pkg_mgr: yum msg: The Python 2 bindings for rpm are needed for this module. If you require Python 3 support use the `dnf` Ansible module instead.

但是 Amazon Lunux 2 不适用于 dnf

这里 和其他论坛也描述了同样的问题。到处建议的解决方案是 Python2.

有什么方法可以使用Python3和yum吗?或者唯一的方法是使用 shell 模块?

根据从 other site 收集的信息, 您可以将 yum 和非 yum 任务分开,并仅将 python3 用于非 yum 任务:

- hosts: testsv
  gather_facts: no
  become: yes
 
  tasks:
    # here yum running under python2 without errors
    - name: task1 
      yum:
        list: curl  

    # here yum running under python3
    - name: task2 
      yum:
        list: curl
      vars:
        ansible_python_interpreter: /usr/bin/python3

或尝试反转条件:

- hosts: testsv
  gather_facts: no
  become: yes
 
  tasks:
    # Run yum under python2, and all other tasks under python3
    - name: task2 
      yum:
        list: curl
      vars:
        ansible_python_interpreter: /usr/bin/python2

@rzlvmp 的解决方案基本有效,谢谢。 但是 yum 无论如何使用默认值 python,因为在 /bin/yum 解释器中是 #!/usr/bin/python

所以,有两个选项:

  1. 使用变量:ansible_python_interpreter: /usr/bin/python3 用于特殊任务,默认使用 Python2。

  2. 编辑/bin/yum:
    #!/usr/bin/python -> #!/usr/bin/python2