Specify Ansible Python interpreter on Task/Host

Sometimes setting a global Python Interpreter isn’t ideal as some hosts and tasks may require different interpreters.

Specify Python Interpreter on Task level

- name: Example Task
  template:
    src: "test.j2"
    dest: "/home/"
    mode: '0600'
  vars:
    ansible_python_interpreter: auto
  delegate_to: '{{some_remote_host}}'

This will select the most appropriate Python interpreter. Should you wish to specify a specific Python interpreter, you can change the ansible_python_interpreter variable as follows:

ansible_python_interpreter: /usr/bin/python3

Specify Python Interpreter on Host level

vars:
    ansible_python_interpreter: /usr/bin/python3
hosts:
    default_python_group:
      ansible_host: x.x.x.x
    python_2_group:
      ansible_host: x.x.x.x
      ansible_python_interpreter: /usr/bin/python2
    python_auto_group:
      ansible_host: x.x.x.x
      ansible_python_interpreter: auto

The hosts in the default_python_group will use the Python 3 interpreter (/usr/bin/python3). The hosts under the python_2_group will use the Python 2 interpreter, and the hosts under the python_auto_group will use the most appropriate Python interpreter for the host on which the playbook runs.