# Install Prometheus server.
#
# @see http://prometheus.io/docs/introduction/getting_started/
#

- name: set internal variables for convenience
  set_fact:
    prometheus_daemon_dir: "{{ prometheus_install_path }}/prometheus-{{ prometheus_version }}.linux-amd64"
    prometheus_tarball_url: "https://github.com/prometheus/prometheus/releases/download/v{{ prometheus_version }}/prometheus-{{ prometheus_version }}.linux-amd64.tar.gz"

- name: set prometheus default options
  set_fact:
    prometheus_default_opts: "{{ prometheus_default_opts }} --web.console.templates={{ prometheus_daemon_dir }}/consoles  --web.console.libraries={{ prometheus_daemon_dir }}/console_libraries"

- name: install python-passlib
  package:
    name: python-passlib
    state: present

- name: download and untar prometheus tarball
  unarchive:
    src: "{{ prometheus_tarball_url }}"
    dest: "{{ prometheus_install_path }}"
    copy: no
    creates: "{{ prometheus_daemon_dir }}"

- name: create prometheus /usr/local/bin links
  file:
    src: "{{ prometheus_daemon_dir }}/{{ item }}"
    dest: "/usr/local/bin/{{ item }}"
    state: link
  loop:
    - "prometheus"
    - "promtool"

- name: mkdir for config and data
  file:
    path: "{{ item }}"
    state: directory
    owner: "{{ prometheus_user }}"
    group: "{{ prometheus_group }}"
    mode: "u=rwx,g=rx,o="
  loop:
    - "{{ prometheus_rule_path }}"
    - "{{ prometheus_file_sd_config_path }}"
    - "{{ prometheus_db_path }}"

- name: copy prometheus systemd config
  template:
    src: "prometheus.service.j2"
    dest: "/lib/systemd/system/prometheus.service"
  notify:
    - reload systemd
    - restart prometheus

- name: copy rule files
  copy:
    src: "{{ item }}"
    dest: "{{ prometheus_rule_path }}/{{ item }}"
    validate: "{{ prometheus_daemon_dir }}/promtool check rules %s"
  loop: "{{ prometheus_rule_files | default([]) }}"
  notify:
    - restart prometheus

- name: copy prometheus main config
  template:
    src: "prometheus.yml.j2"
    dest: "{{ prometheus_config_path }}/prometheus.yml"
    validate: "{{ prometheus_daemon_dir }}/promtool check config %s"
  notify:
    - restart prometheus

- name: enable prometheus service
  service:
    name: prometheus
    enabled: yes
    state: started

- name: create htpasswd
  htpasswd:
    path: /etc/nginx/htpasswd_prometheus
    name: admin
    password: "{{ lookup('passwordstore', 'prometheus/admin') }}"
    owner: root
    group: nginx
    mode: 0640
  notify: restart nginx

- name: write vhost
  template:
    src: prometheus_vhost.conf.j2
    dest: /etc/nginx/conf.d/prometheus.conf
    owner: root
    group: root
    mode: 0644
  notify: restart nginx