Ansible: How to change Python Version

Why not use the var directory in your role...

├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

in vars/main.yml just add....

---                                                                                                                                                                        
# vars file for XXXX
  ansible_python_interpreter: /usr/bin/python3

Per https://docs.ansible.com/ansible/latest/reference_appendices/interpreter_discovery.html you could simply set it in the inventory for that host, or in your configuration file for ansible (which can also be shipped in the same directory as the playbooks and/or inventory):

To control the discovery behavior:

  • for individual hosts and groups, use the ansible_python_interpreter inventory variable
  • globally, use the interpreter_python key in the [defaults] section of ansible.cfg

Adding some points that you might overlook based on comments above:

  • In the original post, the ansible was installed under root account, which in many other environment, you won't use root. In this case, you need to sudo su then install the ansible with pip3, otherwise, it will end up installing for you account only under: ~/.local/bin
  • By new pip version, it's recommended to use python3 -m pip install xxx than directly execute pip3 install xxx