From 29844253c14eadff7aeeb8f0a20d05a0a43431c1 Mon Sep 17 00:00:00 2001
From: Bertrand Lallau <bertrand.lallau@gmail.com>
Date: Sat, 15 Apr 2017 09:31:46 +0200
Subject: [PATCH] Grafana: automatically set InfuxDB datasource

In order to automate Grafana configuration, this fix automatically
set the InfluxDB datasource. This avoid doing a annoying manual
configuration after Kolla-ansible deployment.

Change-Id: I2b1a63fd371966192f1df0a82cee4711c6324710
---
 ansible/roles/grafana/defaults/main.yml     | 14 ++++++++++++++
 ansible/roles/grafana/tasks/deploy.yml      |  3 +++
 ansible/roles/grafana/tasks/post_config.yml | 21 +++++++++++++++++++++
 3 files changed, 38 insertions(+)
 create mode 100644 ansible/roles/grafana/tasks/post_config.yml

diff --git a/ansible/roles/grafana/defaults/main.yml b/ansible/roles/grafana/defaults/main.yml
index 7a5a5ab5e0..e0e4fb8b0b 100644
--- a/ansible/roles/grafana/defaults/main.yml
+++ b/ansible/roles/grafana/defaults/main.yml
@@ -20,6 +20,20 @@ grafana_database_name: "grafana"
 grafana_database_user: "grafana"
 grafana_database_address: "{{ kolla_internal_fqdn }}:{{ database_port }}"
 
+####################
+# Datasource
+####################
+grafana_data_source:
+  isDefault: yes
+  database: "telegraf"
+  user: admin
+  password: "{{ grafana_admin_password }}"
+  name: "telegraf"
+  type: "influxdb"
+  url: "{{ internal_protocol }}://{{ api_interface_address }}:{{ influxdb_http_port }}"
+  access: "proxy"
+  basicAuth: false
+
 ##########
 # Grafana
 ##########
diff --git a/ansible/roles/grafana/tasks/deploy.yml b/ansible/roles/grafana/tasks/deploy.yml
index 44340130de..c12e50dcef 100644
--- a/ansible/roles/grafana/tasks/deploy.yml
+++ b/ansible/roles/grafana/tasks/deploy.yml
@@ -7,3 +7,6 @@
 
 - name: Flush handlers
   meta: flush_handlers
+
+- include: post_config.yml
+  when: inventory_hostname in groups['grafana']
diff --git a/ansible/roles/grafana/tasks/post_config.yml b/ansible/roles/grafana/tasks/post_config.yml
new file mode 100644
index 0000000000..a2742e7359
--- /dev/null
+++ b/ansible/roles/grafana/tasks/post_config.yml
@@ -0,0 +1,21 @@
+---
+- name: Wait for grafana port
+  wait_for:
+    host: "{{ api_interface_address }}"
+    port: "{{ grafana_server_port }}"
+
+- name: Enable influxdb datasource
+  uri:
+    url: "{{ internal_protocol }}://{{ api_interface_address }}:{{ grafana_server_port }}/api/datasources"
+    method: POST
+    user: admin
+    password: "{{ grafana_admin_password }}"
+    body: "{{ grafana_data_source | to_json }}"
+    body_format: json
+    force_basic_auth: yes
+    status_code: 200, 409
+  register: response
+  when: grafana_data_source is defined
+  changed_when: response.status == 200
+  failed_when: response.status not in [200, 409] or
+               response.status == 409 and ("Data source with same name already exists" not in response.json.message|default(""))