Last Updated: August 23, 2019
·
4.923K
· EvanK

On ansible and python 2/3 package juggling

In this playbook I'm writing, I've got several roles, the first of which installs some common packages via the apt module, that are needed for other ansible modules (python-pymysql in this case).

# ...in the "common" role...
- name: Install some common packages
  apt:
    name: "{{ common_packages }}"
  vars:
    common_packages:
      - python-apt
      - python-pymysql
  become: true

Later in a separate role of the same playbook, I get a failed mysql_db task, it claims because of a missing package that's already been installed.

# ...in the "app" role...
- name: Create mysql app database
  mysql_db:
    name: app
    login_user: root
    login_password: some-big-crazy-secure-password
  become: true
# but we JUST installed this :(
TASK [app : Create mysql app database] ****************************************************************************************************************************************************
fatal: [example.com]: FAILED! => {"changed": false, "msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required."}

So I did the most reasonable thing and hopped on IRC:

Ansible Community IRC on freenode

I described my issue in brief and one helpful person said they'd had a similar problem where the packages were installed for the wrong python interpreter and opting for the python3 version fixed their issue. They also directed me to the interpreter discovery documentation where it states that as of 2.8 (the version I am using as it happens), ansible will attempt to guess which python to use unless a specific inventory or config variable is set. (This is a simplification, as it's a very complex and interesting "guess". Read the docs if you're interested!)

# ...in the "common" role...
- name: Install some common packages
  apt:
    name: "{{ common_packages }}"
  vars:
    common_packages:
      - python-apt
      - python-pymysql
      - python3-apt
      - python3-pymysql
  become: true

Since control and remote environments often differ, I chose to install both packages for python 2 and 3. YMMV.