解决 Ansible Python 解释器警告

AnsibleBeginner
立即练习

介绍

在本次挑战中,你将遇到一个与 Python 解释器相关的常见 Ansible 配置问题。在运行 Ansible 命令时,你可能会收到关于默认 Python 解释器的警告。你的任务是通过正确配置 Ansible 来消除这些警告。本次挑战将测试你对 Ansible 配置文件理解能力,并要求你进行必要的调整以优化 Ansible 环境。

这是一个「挑战」,它与「引导实验」的不同之处在于,你需要尝试独立完成挑战任务,而不是按照实验步骤进行学习。挑战通常具有一定的难度。如果你觉得困难,可以与 Labby 讨论或查看解决方案。历史数据显示,这是一个 初学者 级别的挑战,通过率为 97%。它在学习者中获得了 97% 的好评率。

配置 Ansible 使用正确的 Python 解释器

系统已经为你提供了一个预先配置好的 Ansible 环境。当你尝试运行一个简单的 Ansible 命令时,会遇到关于 Python 解释器的警告。你的任务是解决这些警告,并确保 Ansible 命令在运行时没有任何与解释器相关的问题。

要重现这些警告,请在终端中运行以下命令:

ansible all -m ping

你应该会看到类似如下的输出:

[DEPRECATION WARNING]: Distribution ubuntu 22.04 on host localhost should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.10/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[DEPRECATION WARNING]: Distribution ubuntu 22.04 on host web1 should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.10/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
web1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

你的目标是消除这些警告并确保 Ansible 使用 Python 3。

任务

  • 识别运行 Ansible 命令时出现的 Python 解释器警告。
  • 创建一个 Ansible 配置文件来指定正确的 Python 解释器。
  • 再次运行命令,验证警告是否已消除。

要求

  1. 所有操作都应在 /home/labex/project 目录下进行。
  2. /home/labex/project 目录下创建一个名为 ansible.cfg 的 Ansible 配置文件。
  3. 使用适当的配置选项将 Python 解释器设置为 /usr/bin/python3
  4. 清单文件(Inventory file)已经设置在 /etc/ansible/hosts(由初始环境提供)。

示例

正确配置 Ansible 后,运行命令不应产生任何 Python 解释器警告。输出应类似于:

localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
web1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
✨ 查看解决方案并练习

总结

在本次挑战中,你学习了如何解决与 Python 解释器相关的常见 Ansible 配置问题。你遇到了关于已弃用 Python 解释器的警告,并学会了如何配置 Ansible 以改用 Python 3。通过创建 Ansible 配置文件(ansible.cfg)并使用 interpreter_python 选项指定正确的 Python 解释器路径,你确保了 Ansible 使用合适的 Python 版本。这个练习展示了正确配置 Ansible 以使其与系统 Python 环境无缝协作的重要性,这对于避免警告并确保 Ansible 命令的顺畅执行至关重要。