Debian Codegraph @

ansible_collections/community/grafana/plugins/modules/grafana_plugin.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Thierry Sallé (@seuf)
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 DOCUMENTATION = """module: grafana_plugin
10 author:
11 - Thierry Sallé (@seuf)
12 short_description: Manage Grafana plugins via grafana-cli
13 description:
14 - Install and remove Grafana plugins.
15 - See U(https://grafana.com/docs/plugins/installation/) for upstream documentation.
16 options:
17 name:
18 description:
19 - Name of the plugin.
20 required: true
21 type: str
22 version:
23 description:
24 - Version of the plugin to install.
25 - Defaults to C(latest).
26 type: str
27 grafana_plugins_dir:
28 description:
29 - Directory where the Grafana plugin will be installed.
30 - If omitted, defaults to C(/var/lib/grafana/plugins).
31 type: str
32 grafana_repo:
33 description:
34 - URL to the Grafana plugin repository.
35 - 'If omitted, grafana-cli will use the default value: U(https://grafana.com/api/plugins).'
36 type: str
37 grafana_plugin_url:
38 description:
39 - Full URL to the plugin zip file instead of downloading the file from U(https://grafana.com/api/plugins).
40 - Requires grafana 4.6.x or later.
41 type: str
42 state:
43 description:
44 - Whether the plugin should be installed.
45 choices:
46 - present
47 - absent
48 default: present
49 type: str
50 validate_certs:
51 description:
52 - Boolean variable to include --insecure while installing pluging
53 default: false
54 type: bool
55 """
56
57 EXAMPLES = """
58 ---
59 - name: Install/update Grafana piechart panel plugin
60 community.grafana.grafana_plugin:
61 name: grafana-piechart-panel
62 version: latest
63 state: present
64 """
65
66 RETURN = """
67 ---
68 version:
69 description: version of the installed/removed/updated plugin.
70 type: str
71 returned: always
72 """
73
74 import os
75 from ansible.module_utils.basic import AnsibleModule
76
77 __metaclass__ = type
78
79
80 class GrafanaCliException(Exception):
81 pass
82
83
84 def parse_version(string):
85 name, version = string.split("@")
86 return name.strip(), version.strip()
87
88
89 def grafana_cli_bin(params):
90 """
91 Get the grafana-cli binary path with global options.
92 Raise a GrafanaCliException if the grafana-cli is not present or not in PATH
93
94 :param params: ansible module params. Used to fill grafana-cli global params.
95 """
96 program = "grafana-cli"
97 grafana_cli = None
98
99 def is_exe(fpath):
100 return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
101
102 fpath, fname = os.path.split(program)
103 if fpath:
104 if is_exe(program):
105 grafana_cli = program
106 else:
107 for path in os.environ["PATH"].split(os.pathsep):
108 path = path.strip('"')
109 exe_file = os.path.join(path, program)
110 if is_exe(exe_file):
111 grafana_cli = exe_file
112 break
113
114 if grafana_cli is None:
115 raise GrafanaCliException("grafana-cli binary is not present or not in PATH")
116 else:
117 if "grafana_plugin_url" in params and params["grafana_plugin_url"]:
118 grafana_cli = "{0} {1} {2}".format(
119 grafana_cli, "--pluginUrl", params["grafana_plugin_url"]
120 )
121 if "grafana_plugins_dir" in params and params["grafana_plugins_dir"]:
122 grafana_cli = "{0} {1} {2}".format(
123 grafana_cli, "--pluginsDir", params["grafana_plugins_dir"]
124 )
125 if "grafana_repo" in params and params["grafana_repo"]:
126 grafana_cli = "{0} {1} {2}".format(
127 grafana_cli, "--repo", params["grafana_repo"]
128 )
129 if "validate_certs" in params and params["validate_certs"] is False:
130 grafana_cli = "{0} {1}".format(grafana_cli, "--insecure")
131
132 return "{0} {1}".format(grafana_cli, "plugins")
133
134
135 def get_grafana_plugin_version(module, params):
136 """
137 Fetch grafana installed plugin version. Return None if plugin is not installed.
138
139 :param module: ansible module object. used to run system commands.
140 :param params: ansible module params.
141 """
142 grafana_cli = grafana_cli_bin(params)
143 rc, stdout, stderr = module.run_command("{0} ls".format(grafana_cli))
144 stdout_lines = stdout.split("\n")
145 for line in stdout_lines:
146 if line.find(" @ ") != -1:
147 line = line.rstrip()
148 plugin_name, plugin_version = parse_version(line)
149 if plugin_name == params["name"]:
150 return plugin_version
151 return None
152
153
154 def get_grafana_plugin_version_latest(module, params):
155 """
156 Fetch the latest version available from grafana-cli.
157 Return the newest version number or None not found.
158
159 :param module: ansible module object. used to run system commands.
160 :param params: ansible module params.
161 """
162 grafana_cli = grafana_cli_bin(params)
163 rc, stdout, stderr = module.run_command(
164 "{0} list-versions {1}".format(grafana_cli, params["name"])
165 )
166 stdout_lines = stdout.split("\n")
167 if stdout_lines[0]:
168 return stdout_lines[0].rstrip()
169 return None
170
171
172 def grafana_plugin(module, params):
173 """
174 Install update or remove grafana plugin
175
176 :param module: ansible module object. used to run system commands.
177 :param params: ansible module params.
178 """
179 grafana_cli = grafana_cli_bin(params)
180
181 if params["state"] == "present":
182 grafana_plugin_version = get_grafana_plugin_version(module, params)
183 if grafana_plugin_version is not None:
184 if "version" in params and params["version"]:
185 if params["version"] == grafana_plugin_version:
186 return {
187 "msg": "Grafana plugin already installed",
188 "changed": False,
189 "version": grafana_plugin_version,
190 }
191 else:
192 if params["version"] == "latest" or params["version"] is None:
193 latest_version = get_grafana_plugin_version_latest(
194 module, params
195 )
196 if latest_version == grafana_plugin_version:
197 return {
198 "msg": "Grafana plugin already installed",
199 "changed": False,
200 "version": grafana_plugin_version,
201 }
202 cmd = "{0} update {1}".format(grafana_cli, params["name"])
203 else:
204 cmd = "{0} install {1} {2}".format(
205 grafana_cli, params["name"], params["version"]
206 )
207 else:
208 return {
209 "msg": "Grafana plugin already installed",
210 "changed": False,
211 "version": grafana_plugin_version,
212 }
213 else:
214 if "version" in params:
215 if params["version"] == "latest" or params["version"] is None:
216 cmd = "{0} install {1}".format(grafana_cli, params["name"])
217 else:
218 cmd = "{0} install {1} {2}".format(
219 grafana_cli, params["name"], params["version"]
220 )
221 else:
222 cmd = "{0} install {1}".format(grafana_cli, params["name"])
223 else:
224 cmd = "{0} uninstall {1}".format(grafana_cli, params["name"])
225
226 rc, stdout, stderr = module.run_command(cmd, umask=0o0022)
227 if rc == 0:
228 stdout_lines = stdout.split("\n")
229 for line in stdout_lines:
230 if line.find(params["name"]):
231 if line.find(" @ ") != -1:
232 line = line.rstrip()
233 plugin_name, plugin_version = parse_version(line)
234 else:
235 plugin_version = None
236
237 if params["state"] == "present":
238 return {
239 "msg": "Grafana plugin {0} installed : {1}".format(
240 params["name"], cmd
241 ),
242 "changed": True,
243 "version": plugin_version,
244 }
245 else:
246 return {
247 "msg": "Grafana plugin {0} uninstalled : {1}".format(
248 params["name"], cmd
249 ),
250 "changed": True,
251 }
252 else:
253 if params["state"] == "absent" and stdout.find("plugin does not exist"):
254 return {
255 "msg": "Grafana plugin {0} already uninstalled : {1}".format(
256 params["name"], cmd
257 ),
258 "changed": False,
259 }
260 raise GrafanaCliException(
261 "'{0}' execution returned an error : [{1}] {2} {3}".format(
262 cmd, rc, stdout, stderr
263 )
264 )
265
266
267 def main():
268 module = AnsibleModule(
269 argument_spec=dict(
270 name=dict(required=True, type="str"),
271 version=dict(type="str"),
272 grafana_plugins_dir=dict(type="str"),
273 grafana_repo=dict(type="str"),
274 grafana_plugin_url=dict(type="str"),
275 validate_certs=dict(type="bool", default=False),
276 state=dict(choices=["present", "absent"], default="present"),
277 ),
278 supports_check_mode=False,
279 )
280
281 try:
282 result = grafana_plugin(module, module.params)
283 except GrafanaCliException as e:
284 module.fail_json(failed=True, msg="{0}".format(e))
285 return
286 except Exception as e:
287 module.fail_json(failed=True, msg="{0} : {1} ".format(type(e), e))
288 return
289
290 module.exit_json(failed=False, **result)
291 return
292
293
294 if __name__ == "__main__":
295 main()