Fix Ansible Python Version Errors

The Warning

[WARNING]: Platform linux on host webserver is using the discovered Python interpreter at /usr/bin/python3.11,
but future installation of another Python interpreter could change the meaning of that path.
See https://docs.ansible.com/ansible-core/2.17/reference_appendices/interpreter_discovery.html

Solution 1: Set Python Interpreter Globally

# ansible.cfg
[defaults]
interpreter_python = auto_silent  # Suppress warning, use auto-detection

Or specify exactly:

[defaults]
interpreter_python = /usr/bin/python3

Solution 2: Set Per Host in Inventory

[webservers]
web1 ansible_host=192.168.1.10 ansible_python_interpreter=/usr/bin/python3

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

Solution 3: Set in Playbook

- hosts: webservers
  vars:
    ansible_python_interpreter: /usr/bin/python3
  tasks:
    - ansible.builtin.ping:

Common Scenarios

No Python on Remote Host

fatal: [minimal-server]: FAILED! => {
    "msg": "ansible requires a Python interpreter on the target host"
}

Fix with the raw module (doesn't need Python):

- hosts: minimal-server
  gather_facts: false
  tasks:
    - name: Install Python
      ansible.builtin.raw: apt-get install -y python3
      become: true
    
    - name: Now gather facts
      ansible.builtin.setup:

Python 2 vs Python 3 Module Errors

# Force Python 3 for pip modules
- name: Install Python package
  ansible.builtin.pip:
    name: requests
    executable: pip3

Virtualenv Issues

- name: Install in virtualenv
  ansible.builtin.pip:
    name: flask
    virtualenv: /opt/myapp/venv
    virtualenv_python: python3.11

Best Practice

Set it once in ansible.cfg and forget about it:

[defaults]
interpreter_python = auto_silent

This uses auto-detection without the warning. For production, pin the exact version in your inventory.