---
- hosts: my-centos-server
  
  vars:
    mysql_root_password: ASuperSecurePassword
  
  tasks:
  - name: Get YUM repository for MySQL
    get_url:
      url: http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm
      dest: /tmp/mysql57-community-release-el7-7.noarch.rpm
  - name: Install YUM repository for MySQL
    shell: /bin/rpm -Uvh /tmp/mysql57-community-release-el7-7.noarch.rpm
    register: yum_repo_resturn
    failed_when: "'conflict' in yum_repo_return.stderr"
  - name: Install MySQL community server
    yum:
      name: mysql-community-server
      state: present
  - name: Launch MySQL service
    service:
      name: mysqld
      state: started
      enabled: yes
  - name: Install required python MySQLdb lib to create databases and users
    yum:
      name: "{{item}}"
      state: present
    with_items:
      - gcc-c++
      - MySQL-python
  - name: Get temporary MySQL root password
    shell: grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}'
    register: mysql_root_temp_password
  - name: Set the MySQL root password
    shell: mysqladmin -u root --password="{{ mysql_root_temp_password.stdout }}" password "{{ mysql_root_password }}"
    register: mysql_admin_root_password_result
    failed_when: "'(using password: NO)' in mysql_admin_root_password_result.stderr"
  - name: Tune MySQL configuration
    template:
      src: ./resources/my.cnf
      dest: /etc/my.cnf
      mode: 0644
    notify:
      - restart mysqld
  - name: Create my datatable
    mysql_db:
      login_user: root
      login_password: "{{ mysql_root_password }}"
      name: MY_DATATABLE
      encoding: utf8
      collation: utf8_bin
  - name: Create MY_DBA user in MySQL and grant privileges
    mysql_user:
      login_user: root
      login_password: "{{ mysql_root_password }}"
      user: MY_DBA
      password: AnOtherSuperSecurePassword
      host: '%'
      priv: 'MY_DATATABLE.*:ALL'
  
  handlers:
    - name: restart mysqld
      service:
        name: mysqld
        state: restarted