---
# file: roles/mysql/tasks/main.yml

- name: ensure mysql packages are installed for jessie
  apt: name={{ item }} state=latest
  with_items:
    - mysql-server
    - python-mysqldb
  when:
    - debian_version == "jessie"
  tags:
    - packages
    - mysql

- name: ensure mysql packages are installed for stretch
  apt: name={{ item }} state=latest
  with_items:
    - mariadb-server
    - python-mysqldb
  when:
    - debian_version == "stretch"
  tags:
    - packages
    - mysql

- name: ensure mysql is started
  service: name=mysql state=started enabled=yes
  tags:
    - service
    - mysql

- name: ensure the mysql root user exists and has the correct password
  mysql_user:
    name: root
    password: "{{ lookup('passwordstore', 'db/{{ ansible_hostname }}-mysql create=true length=20') }}"
    login_user: root
    login_password: "{{ lookup('passwordstore', 'db/{{ ansible_hostname }}-mysql create=true length=20') }}"
  register: mysql_root_creation_result
  no_log: True
  ignore_errors: yes
  tags:
    - mysql
    - config

- name: initialize the mysql root user
  mysql_user:
    name: root
    password: "{{ lookup('passwordstore', 'db/{{ ansible_hostname }}-mysql create=true length=20') }}"
  no_log: True
  when: mysql_root_creation_result|failed
  tags:
    - mysql
    - config
