---
 - name: Install the MySQL packages
   apt: name={{ item }} state=installed update_cache=yes
   with_items:
     - mysql-server
     - mysql-client
     - python-mysqldb
     - libmysqlclient-dev

 - name: Install mysql.conf
   template:
     src: etc/mysql/mysql.conf.d/mysqld.cnf
     dest: /etc/mysql/mysql.conf.d/mysqld.cnf
   notify: Restart MySQL

 - meta: flush_handlers

 - name: Start + enable the mysql service
   service:
     name: mysql
     state: started
     enabled: true

 - name: Update MySQL root password for all root accounts
   mysql_user: name=root host={{ item }} password={{ secrets.db_password }} state=present
   with_items:
     - "{{ ansible_hostname }}"
     - 127.0.0.1
     - ::1
     - localhost

 - name: Copy the root credentials as .my.cnf file
   template:
     src: root.cnf.j2
     dest: ~/.my.cnf
     mode: 0600

 - name: Ensure Anonymous user(s) are not in the database
   mysql_user: name='' host={{ item }} state=absent
   with_items:
     - localhost
     - "{{ ansible_hostname }}"

 - name: Remove the test database
   mysql_db:
     name: test
     state: absent

---
 ### Update apt cache, but don't mark changed
 # Works around Ansible 2.2 bug
 # TODO: Remove with Ansible 2.3
 - name: Update apt cache
   apt:
     update_cache: yes
   register: apt_cache
   changed_when: False
   failed_when: "apt_cache.cache_updated != True"

 - name: Install the MySQL packages
   apt: name={{ item }} state=installed
   with_items:
     - mysql-server
     - mysql-client
     - python-mysqldb
     - libmysqlclient-dev

 - name: Install mysql.conf
   template:
     src: etc/mysql/mysql.conf.d/mysqld.cnf
     dest: /etc/mysql/mysql.conf.d/mysqld.cnf
   notify: Restart MySQL

 - meta: flush_handlers

 - name: Start + enable the mysql service
   service:
     name: mysql
     state: started
     enabled: true

 - name: Update MySQL root password for all root accounts
   mysql_user: name=root host={{ item }} password={{ secrets.db_password }} state=present
   with_items:
     - "{{ ansible_hostname }}"
     - 127.0.0.1
     - ::1
     - localhost

 - name: Copy the root credentials as .my.cnf file
   template:
     src: root.cnf.j2
     dest: ~/.my.cnf
     mode: 0600

 - name: Ensure Anonymous user(s) are not in the database
   mysql_user: name='' host={{ item }} state=absent
   with_items:
     - localhost
     - "{{ ansible_hostname }}"

 - name: Remove the test database
   mysql_db:
     name: test
     state: absent

Fix Ansible's non-idempotent apt install for MySQL
Fix Ansible's non-idempotent apt install for MySQL

Ansible 2.2 has a bug in the apt module that marks the task as changed,
if the cache is updated. This leads to it always being marked changed.

I've separated out the apt cache update from the package install, and
put in some explicit ok/fail code for the apt update. When Ansible 2.3
comes out, we can remove this silliness.
