- name: fail if exporter host is missing
  fail:
    msg: mysql_target_host is not string
  when: mysql_target_host is not string


- block:
    - include_tasks: init_mysql.yml


    - name: create exporter user
      mysql_user:
        name: "{{ mysql_exporter_username }}"
        password: "{{ mysql_exporter_password }}"
        plugin: mysql_native_password
        host: "{{ container_address | d(ansible_host) }}"
        resource_limits:
          MAX_USER_CONNECTIONS: 3
        priv:
          '*.*': 'SELECT,BINLOG MONITOR,PROCESS'
          'performance_schema.*': SELECT

        login_host: "{{ hostvars[mysql_target_host]['container_address'] | d(hostvars[mysql_target_host]['ansible_host']) }}"
        login_user: "{{ hostvars[mysql_target_host]['mysql_root_username'] | d('root') }}"
        login_password: "{{ hostvars[mysql_target_host]['mysql_root_password'] | d(omit) }}"
      register: result


    - name: flush privileges
      mysql_query:
        query: FLUSH PRIVILEGES
        login_host: "{{ hostvars[mysql_target_host]['container_address'] | d(hostvars[mysql_target_host]['ansible_host']) }}"
        login_user: "{{ hostvars[mysql_target_host]['mysql_root_username'] | d('root') }}"
        login_password: "{{ hostvars[mysql_target_host]['mysql_root_password'] | d(omit) }}"
      when: result.changed

  delegate_to: localhost
