Change Python Version with Ansible

I’m trying to use GNS3 to practice Ansible scripts, and I’m using the built-in version of Ansible from the “Network Automation” Docker instance. Unfortunately, this version of Ansible is still using Python 2.7.

I’ve tried using the command ansible-playbook --version -e 'ansible\_python\_interpreter=/usr/bin/python3' to run a playbook with Python 3, and I’ve also tried specifying the ansible_python_interpreter variable within the playbook:

- name: Common package
  hosts: all
  gather_facts: no
  vars:
    ansible_python_interpreter: /usr/bin/python3
  roles:
    - { role: python, tags: [ init, python, common, addusers] }
...
...

Is there any way I can permanently force Ansible to use Python 3?

To permanently force Ansible to use Python 3, you can set the ansible_python_interpreter variable in your ansible.cfg file.

Here are the steps to do it:

  1. Open the ansible.cfg file. If it doesn’t exist, you can create it in the same directory as your playbook.

  2. Add the following lines to the file:

    [defaults]
    ansible_python_interpreter=/usr/bin/python3
    

    Replace /usr/bin/python3 with the correct path to your Python 3 interpreter if it is different.

  3. Save the file.

By setting the ansible_python_interpreter variable in the ansible.cfg file, Ansible will use Python 3 as the default interpreter for all your playbooks.