importlib.metadata.PackageNotFoundError: No package metadata was found for jinja2

After upgrading Debian 11 to Debian 12 (Bookworm), I’m unable to use ansible or even determine any versions. After the upgrade i had to reinstall packages using apt install python3-%package%.

Output of ansible --version or any other ansible command including running playbooks

Traceback (most recent call last):
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 563, in from_name
    return next(cls.discover(name=name))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/ansible", line 5, in <module>
    from ansible.cli.adhoc import main
  File "/usr/local/lib/python3.11/dist-packages/ansible/cli/__init__.py", line 73, in <module>
    jinja2_version = version('jinja2')
                     ^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 1008, in version
    return distribution(distribution_name).version
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 981, in distribution
    return Distribution.from_name(distribution_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 565, in from_name
    raise PackageNotFoundError(name)
importlib.metadata.PackageNotFoundError: No package metadata was found for jinja2

After triyng to install jinja2 via apt install python3-jinja2 the out put is always

ERROR: 'NoneType' object is not callable

Does someone have an idea on where this is coming from?

My guess would be that you have installed Ansible using pip or pipx in the past, when running Bullseye and that version was fine with the Bullseye version of Python, now you have upgraded Python it doesn’t work.

I’d suggest checking and deleting the files / symlinks in /usr/local/bin, eg:

ls -lah /usr/local/bin/ans*
rm -rf /usr/local/bin/ans*

Then see which version is the default:

which ansible
ansible --version