Debian Codegraph @

ansible_collections/community/general/plugins/modules/datadog_monitor.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Sebastian Kornehl <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: datadog_monitor
11 short_description: Manages Datadog monitors
12 description:
13 - Manages monitors within Datadog.
14 - Options as described on https://docs.datadoghq.com/api/.
15 author: Sebastian Kornehl (@skornehl)
16 requirements: [datadog]
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24 options:
25 api_key:
26 description:
27 - Your Datadog API key.
28 required: true
29 type: str
30 api_host:
31 description:
32 - The URL to the Datadog API. Default value is V(https://api.datadoghq.com).
33 - This value can also be set with the E(DATADOG_HOST) environment variable.
34 type: str
35 version_added: '0.2.0'
36 app_key:
37 description:
38 - Your Datadog app key.
39 required: true
40 type: str
41 state:
42 description:
43 - The designated state of the monitor.
44 - The values V(mute) and V(unmute) are deprecated since community.general 13.0.0 and will be removed in 15.0.0.
45 Use the M(community.general.datadog_downtime) module to manage monitor downtimes instead.
46 required: true
47 choices: ['present', 'absent', 'mute', 'unmute']
48 type: str
49 tags:
50 description:
51 - A list of tags to associate with your monitor when creating or updating.
52 - This can help you categorize and filter monitors.
53 type: list
54 elements: str
55 type:
56 description:
57 - The type of the monitor.
58 - The types V(query alert), V(trace-analytics alert) and V(rum alert) were added in community.general 2.1.0.
59 - The type V(composite) was added in community.general 3.4.0.
60 - The type V(event-v2 alert) was added in community.general 4.8.0.
61 choices:
62 - metric alert
63 - service check
64 - event alert
65 - event-v2 alert
66 - process alert
67 - log alert
68 - query alert
69 - trace-analytics alert
70 - rum alert
71 - composite
72 type: str
73 query:
74 description:
75 - The monitor query to notify on.
76 - Syntax varies depending on what type of monitor you are creating.
77 type: str
78 name:
79 description:
80 - The name of the alert.
81 required: true
82 type: str
83 notification_message:
84 description:
85 - A message to include with notifications for this monitor.
86 - Email notifications can be sent to specific users by using the same '@username' notation as events.
87 - Monitor message template variables can be accessed by using double square brackets, in other words C([[) and C(]]).
88 type: str
89 silenced:
90 type: dict
91 description:
92 - Dictionary of scopes to silence, with timestamps or None.
93 - Each scope is muted until the given POSIX timestamp or forever if the value is V(None).
94 notify_no_data:
95 description:
96 - Whether this monitor notifies when data stops reporting.
97 type: bool
98 default: false
99 no_data_timeframe:
100 description:
101 - The number of minutes before a monitor notifies when data stops reporting.
102 - Must be at least 2x the monitor timeframe for metric alerts or 2 minutes for service checks.
103 - If not specified, it defaults to 2x timeframe for metric, 2 minutes for service.
104 type: str
105 timeout_h:
106 description:
107 - The number of hours of the monitor not reporting data before it automatically resolves from a triggered state.
108 type: str
109 renotify_interval:
110 description:
111 - The number of minutes after the last notification before a monitor re-notifies on the current status.
112 - It only re-notifies if it is not resolved.
113 type: str
114 escalation_message:
115 description:
116 - A message to include with a re-notification. Supports the '@username' notification we allow elsewhere.
117 - Not applicable if O(renotify_interval=none).
118 type: str
119 notify_audit:
120 description:
121 - Whether tagged users are notified on changes to this monitor.
122 type: bool
123 default: false
124 thresholds:
125 type: dict
126 description:
127 - A dictionary of thresholds by status.
128 - Only available for service checks and metric alerts.
129 - Because each of them can have multiple thresholds, we do not define them directly in the query.
130 - "If not specified, it defaults to: V({'ok': 1, 'critical': 1, 'warning': 1})."
131 locked:
132 description:
133 - Whether changes to this monitor should be restricted to the creator or admins.
134 type: bool
135 default: false
136 require_full_window:
137 description:
138 - Whether this monitor needs a full window of data before it gets evaluated.
139 - We highly recommend you set this to V(false) for sparse metrics, otherwise some evaluations are skipped.
140 type: bool
141 new_host_delay:
142 description:
143 - A positive integer representing the number of seconds to wait before evaluating the monitor for new hosts.
144 - This gives the host time to fully initialize.
145 type: str
146 evaluation_delay:
147 description:
148 - Time to delay evaluation (in seconds).
149 - Effective for sparse values.
150 type: str
151 id:
152 description:
153 - The ID of the alert.
154 - If set, it is used instead of O(name) to locate the alert.
155 type: str
156 include_tags:
157 description:
158 - Whether notifications from this monitor automatically inserts its triggering tags into the title.
159 type: bool
160 default: true
161 version_added: 1.3.0
162 priority:
163 description:
164 - Integer from V(1) (high) to V(5) (low) indicating alert severity.
165 type: int
166 version_added: 4.6.0
167 notification_preset_name:
168 description:
169 - Toggles the display of additional content sent in the monitor notification.
170 choices:
171 - show_all
172 - hide_query
173 - hide_handles
174 - hide_all
175 type: str
176 version_added: 7.1.0
177 renotify_occurrences:
178 description:
179 - The number of times re-notification messages should be sent on the current status at the provided re-notification
180 interval.
181 type: int
182 version_added: 7.1.0
183 renotify_statuses:
184 description:
185 - The types of monitor statuses for which re-notification messages are sent.
186 choices:
187 - alert
188 - warn
189 - no data
190 type: list
191 elements: str
192 version_added: 7.1.0
193 """
194
195 EXAMPLES = r"""
196 - name: Create a metric monitor
197 community.general.datadog_monitor:
198 type: "metric alert"
199 name: "Test monitor"
200 state: "present"
201 renotify_interval: 30
202 renotify_occurrences: 1
203 renotify_statuses: ["warn"]
204 notification_preset_name: "show_all"
205 query: "datadog.agent.up.over('host:host1').last(2).count_by_status()"
206 notification_message: "Host [[host.name]] with IP [[host.ip]] is failing to report to datadog."
207 api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"
208 app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
209
210 - name: Deletes a monitor
211 community.general.datadog_monitor:
212 name: "Test monitor"
213 state: "absent"
214 api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"
215 app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
216
217 - name: Mutes a monitor (deprecated, use community.general.datadog_downtime instead)
218 community.general.datadog_monitor:
219 name: "Test monitor"
220 state: "mute"
221 silenced: '{"*":None}'
222 api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"
223 app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
224
225 - name: Unmutes a monitor (deprecated, use community.general.datadog_downtime instead)
226 community.general.datadog_monitor:
227 name: "Test monitor"
228 state: "unmute"
229 api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"
230 app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
231
232 - name: Use datadoghq.eu platform instead of datadoghq.com
233 community.general.datadog_monitor:
234 name: "Test monitor"
235 state: "absent"
236 api_host: https://api.datadoghq.eu
237 api_key: "9775a026f1ca7d1c6c5af9d94d9595a4"
238 app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
239 """
240
241 import traceback
242
243 # Import Datadog
244 DATADOG_IMP_ERR = None
245 try:
246 from datadog import api, initialize
247
248 HAS_DATADOG = True
249 except Exception:
250 DATADOG_IMP_ERR = traceback.format_exc()
251 HAS_DATADOG = False
252
253 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
254
255
256 def main():
257 module = AnsibleModule(
258 argument_spec=dict(
259 api_key=dict(required=True, no_log=True),
260 api_host=dict(),
261 app_key=dict(required=True, no_log=True),
262 state=dict(required=True, choices=["present", "absent", "mute", "unmute"]),
263 type=dict(
264 choices=[
265 "metric alert",
266 "service check",
267 "event alert",
268 "event-v2 alert",
269 "process alert",
270 "log alert",
271 "query alert",
272 "trace-analytics alert",
273 "rum alert",
274 "composite",
275 ]
276 ),
277 name=dict(required=True),
278 query=dict(),
279 notification_message=dict(no_log=True),
280 silenced=dict(type="dict"),
281 notify_no_data=dict(default=False, type="bool"),
282 no_data_timeframe=dict(),
283 timeout_h=dict(),
284 renotify_interval=dict(),
285 escalation_message=dict(),
286 notify_audit=dict(default=False, type="bool"),
287 thresholds=dict(type="dict"),
288 tags=dict(type="list", elements="str"),
289 locked=dict(default=False, type="bool"),
290 require_full_window=dict(type="bool"),
291 new_host_delay=dict(),
292 evaluation_delay=dict(),
293 id=dict(),
294 include_tags=dict(default=True, type="bool"),
295 priority=dict(type="int"),
296 notification_preset_name=dict(choices=["show_all", "hide_query", "hide_handles", "hide_all"]),
297 renotify_occurrences=dict(type="int"),
298 renotify_statuses=dict(type="list", elements="str", choices=["alert", "warn", "no data"]),
299 )
300 )
301
302 # Prepare Datadog
303 if not HAS_DATADOG:
304 module.fail_json(msg=missing_required_lib("datadogpy"), exception=DATADOG_IMP_ERR)
305
306 options = {
307 "api_key": module.params["api_key"],
308 "api_host": module.params["api_host"],
309 "app_key": module.params["app_key"],
310 }
311
312 initialize(**options)
313
314 # Check if api_key and app_key is correct or not
315 # if not, then fail here.
316 response = api.Monitor.get_all()
317 if isinstance(response, dict):
318 msg = response.get("errors", None)
319 if msg:
320 module.fail_json(msg=f"Failed to connect Datadog server using given app_key and api_key : {msg[0]}")
321
322 if module.params["state"] == "present":
323 install_monitor(module)
324 elif module.params["state"] == "absent":
325 delete_monitor(module)
326 elif module.params["state"] == "mute":
327 module.deprecate(
328 "The 'mute' state is deprecated and will be removed in community.general 15.0.0. "
329 "Use the community.general.datadog_downtime module to manage monitor downtimes instead.",
330 version="15.0.0",
331 collection_name="community.general",
332 )
333 mute_monitor(module)
334 elif module.params["state"] == "unmute":
335 module.deprecate(
336 "The 'unmute' state is deprecated and will be removed in community.general 15.0.0. "
337 "Use the community.general.datadog_downtime module to manage monitor downtimes instead.",
338 version="15.0.0",
339 collection_name="community.general",
340 )
341 unmute_monitor(module)
342
343
344 def _fix_template_vars(message):
345 if message:
346 return message.replace("[[", "{{").replace("]]", "}}")
347 return message
348
349
350 def _get_monitor(module):
351 if module.params["id"] is not None:
352 monitor = api.Monitor.get(module.params["id"])
353 if "errors" in monitor:
354 module.fail_json(
355 msg=f"Failed to retrieve monitor with id {module.params['id']}, errors are {monitor['errors']}"
356 )
357 return monitor
358 else:
359 monitors = api.Monitor.get_all()
360 for monitor in monitors:
361 if monitor["name"] == _fix_template_vars(module.params["name"]):
362 return monitor
363 return {}
364
365
366 def _post_monitor(module, options):
367 try:
368 kwargs = dict(
369 type=module.params["type"],
370 query=module.params["query"],
371 name=_fix_template_vars(module.params["name"]),
372 message=_fix_template_vars(module.params["notification_message"]),
373 escalation_message=_fix_template_vars(module.params["escalation_message"]),
374 priority=module.params["priority"],
375 options=options,
376 )
377 if module.params["tags"] is not None:
378 kwargs["tags"] = module.params["tags"]
379 msg = api.Monitor.create(**kwargs)
380 if "errors" in msg:
381 module.fail_json(msg=str(msg["errors"]))
382 else:
383 module.exit_json(changed=True, msg=msg)
384 except Exception as e:
385 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
386
387
388 def _equal_dicts(a, b, ignore_keys):
389 ka = set(a).difference(ignore_keys)
390 kb = set(b).difference(ignore_keys)
391 return ka == kb and all(a[k] == b[k] for k in ka)
392
393
394 def _update_monitor(module, monitor, options):
395 try:
396 kwargs = dict(
397 id=monitor["id"],
398 query=module.params["query"],
399 name=_fix_template_vars(module.params["name"]),
400 message=_fix_template_vars(module.params["notification_message"]),
401 escalation_message=_fix_template_vars(module.params["escalation_message"]),
402 priority=module.params["priority"],
403 options=options,
404 )
405 if module.params["tags"] is not None:
406 kwargs["tags"] = module.params["tags"]
407 msg = api.Monitor.update(**kwargs)
408
409 if "errors" in msg:
410 module.fail_json(msg=str(msg["errors"]))
411 elif _equal_dicts(
412 msg, monitor, ["creator", "overall_state", "modified", "matching_downtimes", "overall_state_modified"]
413 ):
414 module.exit_json(changed=False, msg=msg)
415 else:
416 module.exit_json(changed=True, msg=msg)
417 except Exception as e:
418 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
419
420
421 def install_monitor(module):
422 options = {
423 "silenced": module.params["silenced"],
424 "notify_no_data": module.boolean(module.params["notify_no_data"]),
425 "no_data_timeframe": module.params["no_data_timeframe"],
426 "timeout_h": module.params["timeout_h"],
427 "renotify_interval": module.params["renotify_interval"],
428 "escalation_message": module.params["escalation_message"],
429 "notify_audit": module.boolean(module.params["notify_audit"]),
430 "locked": module.boolean(module.params["locked"]),
431 "require_full_window": module.params["require_full_window"],
432 "new_host_delay": module.params["new_host_delay"],
433 "evaluation_delay": module.params["evaluation_delay"],
434 "include_tags": module.params["include_tags"],
435 "notification_preset_name": module.params["notification_preset_name"],
436 "renotify_occurrences": module.params["renotify_occurrences"],
437 "renotify_statuses": module.params["renotify_statuses"],
438 }
439
440 if module.params["type"] == "service check":
441 options["thresholds"] = module.params["thresholds"] or {"ok": 1, "critical": 1, "warning": 1}
442 if (
443 module.params["type"] in ["metric alert", "log alert", "query alert", "trace-analytics alert", "rum alert"]
444 and module.params["thresholds"] is not None
445 ):
446 options["thresholds"] = module.params["thresholds"]
447
448 monitor = _get_monitor(module)
449 if not monitor:
450 _post_monitor(module, options)
451 else:
452 _update_monitor(module, monitor, options)
453
454
455 def delete_monitor(module):
456 monitor = _get_monitor(module)
457 if not monitor:
458 module.exit_json(changed=False)
459 try:
460 msg = api.Monitor.delete(monitor["id"])
461 module.exit_json(changed=True, msg=msg)
462 except Exception as e:
463 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
464
465
466 def mute_monitor(module):
467 monitor = _get_monitor(module)
468 if not monitor:
469 module.fail_json(msg=f"Monitor {module.params['name']} not found!")
470 elif monitor["options"]["silenced"]:
471 module.fail_json(
472 msg="Monitor is already muted. Datadog does not allow to modify muted alerts, consider unmuting it first."
473 )
474 elif (
475 module.params["silenced"] is not None
476 and len(set(monitor["options"]["silenced"]) ^ set(module.params["silenced"])) == 0
477 ):
478 module.exit_json(changed=False)
479 try:
480 if module.params["silenced"] is None or module.params["silenced"] == "":
481 msg = api.Monitor.mute(id=monitor["id"])
482 else:
483 msg = api.Monitor.mute(id=monitor["id"], silenced=module.params["silenced"])
484 module.exit_json(changed=True, msg=msg)
485 except Exception as e:
486 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
487
488
489 def unmute_monitor(module):
490 monitor = _get_monitor(module)
491 if not monitor:
492 module.fail_json(msg=f"Monitor {module.params['name']} not found!")
493 elif not monitor["options"]["silenced"]:
494 module.exit_json(changed=False)
495 try:
496 msg = api.Monitor.unmute(monitor["id"])
497 module.exit_json(changed=True, msg=msg)
498 except Exception as e:
499 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
500
501
502 if __name__ == "__main__":
503 main()