'Ansible - The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required

My ansible code looks like this:

---
- name: Install python
  apt:
    pkg: "{{ item }}"
    update-cache: yes
    state: latest
  with_items:
    - python
    - python-dev

- name: Install pymysql
  pip:
    name: "{{ item }}"
    executable: pip
    state: present
  with_items:
    - PyMySQL==0.7.11
    - MySQL-python

- name: Install mysql and deps
  apt:
    pkg: "{{ item }}"
    update-cache: yes
    state: latest
  with_items:
    - mysql-server
    - libmysqlclient-dev
    - python-mysqldb
    - python-pip

- name: Create DB
  mysql_db:
    name: "{{ item }}"
    collation: utf8_general_ci
    encoding: utf8
  with_items: "{{ database_names }}"

When I run it, I get the error,

failed: [xxxxx] (item=xxxxx) => {"ansible_loop_var": "item", "changed": false, "item": "xxxxx", "msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required."}

But from my sensible code you see I installed both PyMySQL and MySQL-python prior to calling mysql_db. Also, from ansible runtime log, I see both PyMySQL and MySQL-python got installed successfully:

TASK [mysql : Install python] **************************************************
ok: [aquila] => (item=python)
ok: [aquila] => (item=python-dev)

TASK [mysql : Install pymysql] *************************************************
ok: [aquila] => (item=PyMySQL==0.7.11)
ok: [aquila] => (item=MySQL-python)

TASK [mysql : Install mysql and deps] ******************************************
ok: [aquila] => (item=mysql-server)
ok: [aquila] => (item=libmysqlclient-dev)
ok: [aquila] => (item=python-mysqldb)
ok: [aquila] => (item=python-pip)

TASK [mysql : Create DB] ************************************************
failed: [xxxxx] (item=xxxxx) => {"ansible_loop_var": "item", "changed": false, "item": "aquila", "msg": "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required."}

Why mysql-db is not getting the PyMySQL or MySQL-python module?



Solution 1:[1]

I have the same error on CentOS 7, but on Ubuntu 20.04 this works for me:

- name: Install pip
  apt:
    name: python3-pip
    state: present

- name: Install PyMySQL
  pip:
    name: pymysql
    state: present

UPD: Here's a solution on CentOS 7:

- name: Install MySQL-python
  yum:
    name:
      - python3-pip
      - MySQL-python

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1