Debian Codegraph @

ansible_collections/community/grafana/plugins/lookup/grafana_dashboard.py

raw
1 # (c) 2018 Ansible Project
2 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import absolute_import, division, print_function
4
5 __metaclass__ = type
6
7 DOCUMENTATION = """
8 name: grafana_dashboard
9 author: Thierry Salle (@seuf)
10 short_description: list or search grafana dashboards
11 description:
12 - This lookup returns a list of grafana dashboards with possibility to filter them by query.
13 options:
14 grafana_url:
15 description: url of grafana.
16 env:
17 - name: GRAFANA_URL
18 default: http://127.0.0.1:3000
19 grafana_api_key:
20 description:
21 - Grafana API key.
22 - When C(grafana_api_key) is set, the options C(grafana_user), C(grafana_password) and C(grafana_org_id) are ignored.
23 env:
24 - name: GRAFANA_API_KEY
25 grafana_user:
26 description: grafana authentication user.
27 env:
28 - name: GRAFANA_USER
29 default: admin
30 grafana_password:
31 description: grafana authentication password.
32 env:
33 - name: GRAFANA_PASSWORD
34 default: admin
35 grafana_org_id:
36 description: grafana organisation id.
37 env:
38 - name: GRAFANA_ORG_ID
39 default: 1
40 search:
41 description: optional filter for dashboard search.
42 env:
43 - name: GRAFANA_DASHBOARD_SEARCH
44 validate_certs:
45 description: flag to control SSL certificate validation
46 type: boolean
47 default: true
48 ca_path:
49 description: string of the file system path to CA cert bundle to use for validation
50 type: string
51 """
52
53 EXAMPLES = """
54 - name: get project foo grafana dashboards
55 set_fact:
56 grafana_dashboards: "{{ lookup('grafana_dashboard', 'grafana_url=http://grafana.company.com grafana_user=admin grafana_password=admin search=foo') }}"
57
58 - name: get all grafana dashboards
59 set_fact:
60 grafana_dashboards: "{{ lookup('grafana_dashboard', 'grafana_url=http://grafana.company.com grafana_api_key=' ~ grafana_api_key) }}"
61
62 - name: get project foo grafana dashboards (validate SSL certificates of the instance with custom CA Certificate Bundle)
63 set_fact:
64 grafana_dashboards: |
65 {{
66 lookup(
67 'grafana_dashboard',
68 'grafana_url=https://grafana.company.com grafana_user=admin grafana_password=admin search=foo',
69 validate_certs=true,
70 ca_path='/path/to/chain.crt'
71 )
72 }}
73 """
74
75 import json
76 import os
77 from ansible.errors import AnsibleError
78 from ansible.plugins.lookup import LookupBase
79 from ansible.module_utils.urls import basic_auth_header, open_url, SSLValidationError
80 from ansible.module_utils._text import to_native
81 from ansible.module_utils.six.moves.urllib.error import HTTPError
82 from ansible.utils.display import Display
83
84 display = Display()
85
86
87 ANSIBLE_GRAFANA_URL = "http://127.0.0.1:3000"
88 ANSIBLE_GRAFANA_API_KEY = None
89 ANSIBLE_GRAFANA_USER = "admin"
90 ANSIBLE_GRAFANA_PASSWORD = "admin"
91 ANSIBLE_GRAFANA_ORG_ID = 1
92 ANSIBLE_GRAFANA_DASHBOARD_SEARCH = None
93
94 if os.getenv("GRAFANA_URL") is not None:
95 ANSIBLE_GRAFANA_URL = os.environ["GRAFANA_URL"]
96
97 if os.getenv("GRAFANA_API_KEY") is not None:
98 ANSIBLE_GRAFANA_API_KEY = os.environ["GRAFANA_API_KEY"]
99
100 if os.getenv("GRAFANA_USER") is not None:
101 ANSIBLE_GRAFANA_USER = os.environ["GRAFANA_USER"]
102
103 if os.getenv("GRAFANA_PASSWORD") is not None:
104 ANSIBLE_GRAFANA_PASSWORD = os.environ["GRAFANA_PASSWORD"]
105
106 if os.getenv("GRAFANA_ORG_ID") is not None:
107 ANSIBLE_GRAFANA_ORG_ID = os.environ["GRAFANA_ORG_ID"]
108
109 if os.getenv("GRAFANA_DASHBOARD_SEARCH") is not None:
110 ANSIBLE_GRAFANA_DASHBOARD_SEARCH = os.environ["GRAFANA_DASHBOARD_SEARCH"]
111
112
113 class GrafanaAPIException(Exception):
114 pass
115
116
117 class GrafanaAPI:
118 def __init__(self, validate_certs, ca_path, **kwargs):
119 self.grafana_url = kwargs.get("grafana_url", ANSIBLE_GRAFANA_URL)
120 self.grafana_api_key = kwargs.get("grafana_api_key", ANSIBLE_GRAFANA_API_KEY)
121 self.grafana_user = kwargs.get("grafana_user", ANSIBLE_GRAFANA_USER)
122 self.grafana_password = kwargs.get("grafana_password", ANSIBLE_GRAFANA_PASSWORD)
123 self.grafana_org_id = kwargs.get("grafana_org_id", ANSIBLE_GRAFANA_ORG_ID)
124 self.search = kwargs.get("search", ANSIBLE_GRAFANA_DASHBOARD_SEARCH)
125 self.validate_certs = validate_certs
126 self.ca_path = ca_path
127
128 def grafana_switch_organisation(self, headers):
129 try:
130 r = open_url(
131 "%s/api/user/using/%s" % (self.grafana_url, self.grafana_org_id),
132 headers=headers,
133 method="POST",
134 validate_certs=self.validate_certs,
135 ca_path=self.ca_path,
136 )
137 except HTTPError as e:
138 raise GrafanaAPIException(
139 "Unable to switch to organization %s : %s"
140 % (self.grafana_org_id, to_native(e))
141 )
142 except SSLValidationError as e:
143 raise GrafanaAPIException(
144 "Unable to validate server's certificate with %s: %s"
145 % (self.ca_path, to_native(e))
146 )
147 if r.getcode() != 200:
148 raise GrafanaAPIException(
149 "Unable to switch to organization %s : %s"
150 % (self.grafana_org_id, str(r.getcode()))
151 )
152
153 def grafana_headers(self):
154 headers = {"content-type": "application/json; charset=utf8"}
155 if self.grafana_api_key:
156 headers["Authorization"] = "Bearer %s" % self.grafana_api_key
157 else:
158 headers["Authorization"] = basic_auth_header(
159 self.grafana_user, self.grafana_password
160 )
161 self.grafana_switch_organisation(headers)
162
163 return headers
164
165 def grafana_list_dashboards(self):
166 # define http headers
167 headers = self.grafana_headers()
168
169 dashboard_list = []
170 try:
171 if self.search:
172 r = open_url(
173 "%s/api/search?query=%s" % (self.grafana_url, self.search),
174 headers=headers,
175 method="GET",
176 validate_certs=self.validate_certs,
177 ca_path=self.ca_path,
178 )
179 else:
180 r = open_url(
181 "%s/api/search/" % self.grafana_url,
182 headers=headers,
183 method="GET",
184 validate_certs=self.validate_certs,
185 ca_path=self.ca_path,
186 )
187 except HTTPError as e:
188 raise GrafanaAPIException("Unable to search dashboards : %s" % to_native(e))
189 except SSLValidationError as e:
190 raise GrafanaAPIException(
191 "Unable to validate server's certificate with %s: %s"
192 % (self.ca_path, to_native(e))
193 )
194 if r.getcode() == 200:
195 try:
196 dashboard_list = json.loads(r.read())
197 except Exception as e:
198 raise GrafanaAPIException("Unable to parse json list %s" % to_native(e))
199 else:
200 raise GrafanaAPIException(
201 "Unable to list grafana dashboards : %s" % str(r.getcode())
202 )
203
204 return dashboard_list
205
206
207 class LookupModule(LookupBase):
208 def run(self, terms, variables=None, **kwargs):
209 self.set_options(var_options=variables, direct=kwargs)
210 grafana_args = terms[0].split(" ")
211 grafana_dict = {}
212 ret = []
213
214 for param in grafana_args:
215 try:
216 key, value = param.split("=", 1)
217 except ValueError:
218 raise AnsibleError(
219 "grafana_dashboard lookup plugin needs key=value pairs, but received %s"
220 % terms
221 )
222 grafana_dict[key] = value
223
224 grafana = GrafanaAPI(
225 validate_certs=self.get_option("validate_certs"),
226 ca_path=self.get_option("ca_path"),
227 **grafana_dict,
228 )
229
230 ret = grafana.grafana_list_dashboards()
231
232 return ret