Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import absolute_import, division, print_function
19
20 __metaclass__ = type
21
22 DOCUMENTATION = """
23 ---
24 module: grafana_contact_point
25 author:
26 - Moritz Pötschk (@nemental)
27 version_added: "2.0.0"
28 short_description: Manage Grafana Contact Points
29 description:
30 - Create/Update/Delete Grafana Contact Points via API.
31 options:
32 disable_resolve_message:
33 description:
34 - Disables the resolve message.
35 type: bool
36 default: false
37 include_image:
38 description:
39 - Whether to include an image in the notification.
40 type: bool
41 default: false
42 name:
43 description:
44 - The name of the contact point.
45 - Required when C(state) is C(present).
46 type: str
47 org_id:
48 description:
49 - The organization ID.
50 type: int
51 default: 1
52 org_name:
53 description:
54 - The name of the organization.
55 type: str
56 provisioning:
57 description:
58 - Indicates if provisioning is enabled.
59 type: bool
60 default: true
61 state:
62 description:
63 - Status of the contact point.
64 type: str
65 default: present
66 choices:
67 - present
68 - absent
69 type:
70 description:
71 - The type of the contact point.
72 - Required when C(state) is C(present).
73 type: str
74 choices:
75 - alertmanager
76 - dingding
77 - discord
78 - email
79 - googlechat
80 - kafka
81 - line
82 - opsgenie
83 - pagerduty
84 - pushover
85 - sensugo
86 - slack
87 - teams
88 - telegram
89 - threema
90 - victorops
91 - webex
92 - webhook
93 - wecom
94 uid:
95 description:
96 - The unique ID of the contact point.
97 - Normally the uid is generated randomly, but it is required for handling the contact point via API.
98 type: str
99 required: true
100 alertmanager_password:
101 description:
102 - Password for accessing Alertmanager.
103 type: str
104 alertmanager_url:
105 description:
106 - URL for accessing Alertmanager.
107 - Required when C(type) is C(alertmanager).
108 type: str
109 alertmanager_username:
110 description:
111 - Username for accessing Alertmanager.
112 type: str
113 dingding_message:
114 description:
115 - The message to send via DingDing.
116 type: str
117 dingding_message_type:
118 description:
119 - The type of message to send via DingDing.
120 type: str
121 dingding_title:
122 description:
123 - The title of the DingDing message.
124 type: str
125 dingding_url:
126 description:
127 - The URL for DingDing webhook.
128 - Required when C(type) is C(dingding).
129 type: str
130 discord_avatar_url:
131 description:
132 - The avatar URL for Discord messages.
133 type: str
134 discord_message:
135 description:
136 - The message to send via Discord.
137 type: str
138 discord_title:
139 description:
140 - The title of the Discord message.
141 type: str
142 discord_url:
143 description:
144 - The URL for Discord webhook.
145 - Required when C(type) is C(discord).
146 type: str
147 discord_use_username:
148 description:
149 - Whether to use a custom username in Discord.
150 type: bool
151 default: false
152 email_addresses:
153 description:
154 - List of email addresses to send the message to.
155 - Required when C(type) is C(email).
156 type: list
157 elements: str
158 email_message:
159 description:
160 - The content of the email message.
161 type: str
162 email_single:
163 description:
164 - Whether to send a single email or individual emails.
165 type: bool
166 default: false
167 email_subject:
168 description:
169 - The subject of the email.
170 type: str
171 googlechat_url:
172 description:
173 - The URL for Google Chat webhook.
174 - Required when C(type) is C(webhook).
175 type: str
176 googlechat_message:
177 description:
178 - The message to send via Google Chat.
179 type: str
180 googlechat_title:
181 description:
182 - The title of the Google Chat message.
183 type: str
184 kafka_api_version:
185 description:
186 - The API version for Kafka.
187 type: str
188 default: v2
189 kafka_cluster_id:
190 description:
191 - The cluster ID for Kafka.
192 type: str
193 kafka_description:
194 description:
195 - The description for the Kafka configuration.
196 type: str
197 kafka_details:
198 description:
199 - Additional details for Kafka.
200 type: str
201 kafka_password:
202 description:
203 - Password for accessing Kafka.
204 type: str
205 kafka_rest_proxy_url:
206 description:
207 - URL for Kafka REST Proxy.
208 - Required when C(type) is C(kafka).
209 type: str
210 kafka_topic:
211 description:
212 - Kafka topic to publish to.
213 - Required when C(type) is C(kafka).
214 type: str
215 kafka_username:
216 description:
217 - Username for accessing Kafka.
218 type: str
219 line_description:
220 description:
221 - Description for the Line message.
222 type: str
223 line_title:
224 description:
225 - Title of the Line message.
226 type: str
227 line_token:
228 description:
229 - Access token for Line.
230 - Required when C(type) is C(line).
231 type: str
232 opsgenie_api_key:
233 description:
234 - API key for OpsGenie.
235 - Required when C(type) is C(opsgenie).
236 type: str
237 opsgenie_auto_close:
238 description:
239 - Whether to enable auto-closing of alerts in OpsGenie.
240 type: bool
241 opsgenie_description:
242 description:
243 - Description of the OpsGenie alert.
244 type: str
245 opsgenie_message:
246 description:
247 - Message to send via OpsGenie.
248 type: str
249 opsgenie_override_priority:
250 description:
251 - Whether to override the priority in OpsGenie.
252 type: bool
253 opsgenie_responders:
254 description:
255 - List of responders for OpsGenie alerts.
256 type: list
257 elements: dict
258 opsgenie_send_tags_as:
259 description:
260 - Format for sending tags in OpsGenie.
261 type: str
262 opsgenie_url:
263 description:
264 - URL for OpsGenie webhook.
265 - Required when C(type) is C(pagerduty).
266 type: str
267 pagerduty_class:
268 description:
269 - Class of the PagerDuty alert.
270 type: str
271 pagerduty_client:
272 description:
273 - Client identifier for PagerDuty.
274 type: str
275 pagerduty_client_url:
276 description:
277 - Client URL for PagerDuty.
278 type: str
279 pagerduty_component:
280 description:
281 - Component involved in the PagerDuty alert.
282 type: str
283 pagerduty_details:
284 description:
285 - List of additional details for PagerDuty.
286 type: list
287 elements: dict
288 pagerduty_group:
289 description:
290 - Group associated with the PagerDuty alert.
291 type: str
292 pagerduty_integration_key:
293 description:
294 - Integration key for PagerDuty.
295 - Required when C(type) is C(pagerduty).
296 type: str
297 pagerduty_severity:
298 description:
299 - Severity level of the PagerDuty alert.
300 type: str
301 choices:
302 - critical
303 - error
304 - warning
305 - info
306 pagerduty_source:
307 description:
308 - Source of the PagerDuty alert.
309 type: str
310 pagerduty_summary:
311 description:
312 - Summary of the PagerDuty alert.
313 type: str
314 pushover_api_token:
315 description:
316 - API token for Pushover.
317 - Required when C(type) is C(pushover).
318 type: str
319 pushover_devices:
320 description:
321 - List of devices for Pushover notifications.
322 type: list
323 elements: str
324 pushover_expire:
325 description:
326 - Expiration time for Pushover notifications.
327 type: int
328 pushover_message:
329 description:
330 - Message to send via Pushover.
331 type: str
332 pushover_ok_priority:
333 description:
334 - Priority for OK messages in Pushover.
335 type: int
336 pushover_ok_sound:
337 description:
338 - Sound for OK messages in Pushover.
339 type: str
340 pushover_priority:
341 description:
342 - Priority for Pushover messages.
343 type: int
344 pushover_retry:
345 description:
346 - Retry interval for Pushover messages.
347 type: int
348 pushover_sound:
349 description:
350 - Sound for Pushover notifications.
351 type: str
352 pushover_title:
353 description:
354 - Title of the Pushover message.
355 type: str
356 pushover_upload_image:
357 description:
358 - Whether to upload an image with Pushover notification.
359 type: bool
360 default: true
361 pushover_user_key:
362 description:
363 - User key for Pushover.
364 - Required when C(type) is C(pushover).
365 type: str
366 sensugo_api_key:
367 description:
368 - API key for Sensu Go.
369 - Required when C(type) is C(pushover).
370 type: str
371 sensugo_url:
372 description:
373 - URL for Sensu Go.
374 - Required when C(type) is C(sensugo).
375 type: str
376 sensugo_check:
377 description:
378 - Check name for Sensu Go.
379 type: str
380 sensugo_entity:
381 description:
382 - Entity name for Sensu Go.
383 type: str
384 sensugo_handler:
385 description:
386 - Handler for Sensu Go.
387 type: str
388 sensugo_message:
389 description:
390 - Message to send via Sensu Go.
391 type: str
392 sensugo_namespace:
393 description:
394 - Namespace for Sensu Go.
395 type: str
396 slack_endpoint_url:
397 description:
398 - Endpoint URL for Slack webhook.
399 type: str
400 slack_icon_emoji:
401 description:
402 - Icon emoji for Slack messages.
403 type: str
404 slack_icon_url:
405 description:
406 - Icon URL for Slack messages.
407 type: str
408 slack_mention_channel:
409 description:
410 - Channel mention for Slack messages.
411 type: str
412 choices:
413 - here
414 - channel
415 slack_mention_groups:
416 description:
417 - List of groups to mention in Slack messages.
418 type: list
419 elements: str
420 slack_mention_users:
421 description:
422 - List of users to mention in Slack messages.
423 type: list
424 elements: str
425 slack_recipient:
426 description:
427 - Recipient for Slack messages.
428 - Required when C(type) is C(slack).
429 type: str
430 slack_text:
431 description:
432 - Text content for Slack messages.
433 type: str
434 slack_title:
435 description:
436 - Title of the Slack message.
437 type: str
438 slack_token:
439 description:
440 - Token for Slack authentication.
441 - Required when C(type) is C(slack).
442 type: str
443 slack_url:
444 description:
445 - URL for Slack webhook.
446 - Required when C(type) is C(slack).
447 type: str
448 slack_username:
449 description:
450 - Username to use in Slack messages.
451 type: str
452 teams_message:
453 description:
454 - Message to send via Microsoft Teams.
455 type: str
456 teams_section_title:
457 description:
458 - Section title for Microsoft Teams messages.
459 type: str
460 teams_title:
461 description:
462 - Title of the Microsoft Teams message.
463 type: str
464 teams_url:
465 description:
466 - URL for Microsoft Teams webhook.
467 - Required when C(type) is C(teams).
468 type: str
469 telegram_chat_id:
470 description:
471 - Chat ID for Telegram.
472 - Required when C(type) is C(telegram).
473 type: str
474 telegram_disable_notifications:
475 description:
476 - Whether to disable notifications for Telegram messages.
477 type: bool
478 telegram_message:
479 description:
480 - Message to send via Telegram.
481 type: str
482 telegram_parse_mode:
483 description:
484 - Parse mode for Telegram messages.
485 type: str
486 telegram_protect_content:
487 description:
488 - Whether to protect content in Telegram messages.
489 type: bool
490 telegram_token:
491 description:
492 - Token for Telegram authentication.
493 - Required when C(type) is C(telegram).
494 type: str
495 telegram_web_page_view:
496 description:
497 - Whether to enable web page preview in Telegram messages.
498 type: bool
499 threema_api_secret:
500 description:
501 - API secret for Threema.
502 - Required when C(type) is C(threema).
503 type: str
504 threema_description:
505 description:
506 - Description for Threema messages.
507 type: str
508 threema_gateway_id:
509 description:
510 - Gateway ID for Threema.
511 - Required when C(type) is C(threema).
512 type: str
513 threema_recipient_id:
514 description:
515 - Recipient ID for Threema messages.
516 - Required when C(type) is C(threema).
517 type: str
518 threema_title:
519 description:
520 - Title of the Threema message.
521 type: str
522 victorops_description:
523 description:
524 - Description for VictorOps messages.
525 type: str
526 victorops_message_type:
527 description:
528 - Message type for VictorOps.
529 type: str
530 choices:
531 - CRITICAL
532 - RECOVERY
533 victorops_title:
534 description:
535 - Title of the VictorOps message.
536 type: str
537 victorops_url:
538 description:
539 - URL for VictorOps webhook.
540 - Required when C(type) is C(victorops).
541 type: str
542 webex_api_url:
543 description:
544 - API URL for Webex.
545 type: str
546 webex_message:
547 description:
548 - Message to send via Webex.
549 type: str
550 webex_room_id:
551 description:
552 - Room ID for Webex messages.
553 - Required when C(type) is C(webex).
554 type: str
555 webex_token:
556 description:
557 - Token for Webex authentication.
558 - Required when C(type) is C(webex).
559 type: str
560 webhook_authorization_credentials:
561 description:
562 - Authorization credentials for webhook.
563 type: str
564 webhook_authorization_scheme:
565 description:
566 - Authorization scheme for webhook.
567 type: str
568 webhook_http_method:
569 description:
570 - HTTP method for webhook.
571 type: str
572 choices:
573 - POST
574 - PUT
575 webhook_max_alerts:
576 description:
577 - Maximum number of alerts for webhook.
578 type: int
579 webhook_message:
580 description:
581 - Message to send via webhook.
582 type: str
583 webhook_password:
584 description:
585 - Password for webhook authentication.
586 type: str
587 webhook_title:
588 description:
589 - Title of the webhook message.
590 type: str
591 webhook_url:
592 description:
593 - URL for webhook.
594 - Required when C(type) is C(webhook).
595 type: str
596 webhook_username:
597 description:
598 - Username for webhook authentication.
599 type: str
600 wecom_agent_id:
601 description:
602 - Agent ID for WeCom.
603 - Required when C(type) is C(wecom).
604 type: str
605 wecom_corp_id:
606 description:
607 - Corporate ID for WeCom.
608 - Required when C(type) is C(wecom).
609 type: str
610 wecom_message:
611 description:
612 - Message to send via WeCom.
613 type: str
614 wecom_msg_type:
615 description:
616 - Message type for WeCom.
617 type: str
618 wecom_secret:
619 description:
620 - Secret for WeCom authentication.
621 - Required when C(type) is C(wecom).
622 type: str
623 wecom_title:
624 description:
625 - Title of the WeCom message.
626 type: str
627 wecom_to_user:
628 description:
629 - List of users to send the WeCom message to.
630 type: list
631 elements: str
632 wecom_url:
633 description:
634 - URL for WeCom webhook.
635 - Required when C(type) is C(wecom).
636 type: str
637 extends_documentation_fragment:
638 - community.grafana.basic_auth
639 - community.grafana.api_key
640 """
641
642
643 EXAMPLES = """
644 - name: Create email contact point
645 community.grafana.grafana_contact_point:
646 grafana_url: "{{ grafana_url }}"
647 grafana_user: "{{ grafana_username }}"
648 grafana_password: "{{ grafana_password }}"
649 uid: email
650 name: E-Mail
651 type: email
652 email_addresses:
653 - [email protected]
654
655 - name: Delete email contact point
656 community.grafana.grafana_contact_point:
657 grafana_url: "{{ grafana_url }}"
658 grafana_user: "{{ grafana_username }}"
659 grafana_password: "{{ grafana_password }}"
660 uid: email
661 state: absent
662 """
663
664 RETURN = """
665 contact_point:
666 description: Contact point created or updated by the module.
667 returned: success
668 type: complex
669 contains:
670 uid:
671 description: The uid of the contact point.
672 returned: success
673 type: str
674 sample:
675 - ddmyrs0f74t8hc
676 name:
677 description: The name of the contact point.
678 returned: success
679 type: str
680 sample:
681 - supportmail
682 type:
683 description: The type of the contact point.
684 returned: success
685 type: str
686 sample:
687 - email
688 disableResolveMessage:
689 description: Is the resolve message of the contact point disabled.
690 returned: success
691 type: bool
692 sample:
693 - false
694 settings:
695 description: The type specific settings of the contact point.
696 returned: success
697 type: dict
698 sample:
699 - addresses: "[email protected]"
700 singleEmail: false
701 secureFields:
702 description: The secure fields config of the contact point.
703 returned: success
704 type: dict
705 diff:
706 description: Difference between previous and updated contact point.
707 returned: changed
708 type: complex
709 contains:
710 before:
711 description: Previous contact point.
712 returned: changed
713 type: dict
714 sample:
715 - uid: ddmyrs0f74t8hc
716 name: supportmail
717 type: email
718 disableResolveMessage: false
719 settings:
720 addresses: [email protected]
721 singleEmail: false
722 secureFields: {}
723 after:
724 description: Current contact point.
725 returned: changed
726 type: dict
727 sample:
728 - uid: ddmyrs0f74t8hc
729 name: supportmail
730 type: email
731 disableResolveMessage: true
732 settings:
733 addresses: [email protected]
734 singleEmail: false
735 secureFields: {}
736 """
737
738 import json
739
740 from ansible.module_utils.basic import AnsibleModule
741 from ansible.module_utils.urls import fetch_url
742 from ansible.module_utils._text import to_text
743 from ansible_collections.community.grafana.plugins.module_utils.base import (
744 grafana_argument_spec,
745 clean_url,
746 )
747 from ansible.module_utils.urls import basic_auth_header
748
749
750 class GrafanaAPIException(Exception):
751 pass
752
753
754 def grafana_contact_point_payload(data):
755 payload = {
756 "uid": data["uid"],
757 "name": data["name"],
758 "type": data["type"],
759 "disableResolveMessage": data["disable_resolve_message"],
760 "settings": {},
761 }
762
763 if data["type"] == "alertmanager":
764 payload["type"] = "prometheus-alertmanager"
765
766 type_settings_map = {
767 "alertmanager": {
768 "basicAuthPassword": "alertmanager_password",
769 "url": "alertmanager_url",
770 "basicAuthUser": "alertmanager_username",
771 },
772 "dingding": {
773 "message": "dingding_message",
774 "msgType": "dingding_message_type",
775 "title": "dingding_title",
776 "url": "dingding_url",
777 },
778 "discord": {
779 "avatar_url": "discord_avatar_url",
780 "message": "discord_message",
781 "title": "discord_title",
782 "url": "discord_url",
783 "use_discord_username": "discord_use_username",
784 },
785 "email": {
786 "addresses": "email_addresses",
787 "message": "email_message",
788 "singleEmail": "email_single",
789 "subject": "email_subject",
790 },
791 "googlechat": {
792 "url": "googlechat_url",
793 "message": "googlechat_message",
794 "title": "googlechat_title",
795 },
796 "kafka": {
797 "apiVersion": "kafka_api_version",
798 "kafkaClusterId": "kafka_cluster_id",
799 "description": "kafka_description",
800 "details": "kafka_details",
801 "password": "kafka_password",
802 "kafkaRestProxy": "kafka_rest_proxy_url",
803 "kafkaTopic": "kafka_topic",
804 "username": "kafka_username",
805 },
806 "line": {
807 "description": "line_description",
808 "title": "line_title",
809 "token": "line_token",
810 },
811 "opsgenie": {
812 "apiKey": "opsgenie_api_key",
813 "autoClose": "opsgenie_auto_close",
814 "description": "opsgenie_description",
815 "message": "opsgenie_message",
816 "overridePriority": "opsgenie_override_priority",
817 "responders": "opsgenie_responders",
818 "sendTagsAs": "opsgenie_send_tags_as",
819 "apiUrl": "opsgenie_url",
820 },
821 "pagerduty": {
822 "class": "pagerduty_class",
823 "client": "pagerduty_client",
824 "client_url": "pagerduty_client_url",
825 "component": "pagerduty_component",
826 "details": "pagerduty_details",
827 "group": "pagerduty_group",
828 "integrationKey": "pagerduty_integration_key",
829 "severity": "pagerduty_severity",
830 "source": "pagerduty_source",
831 "summary": "pagerduty_summary",
832 },
833 "pushover": {
834 "apiToken": "pushover_api_token",
835 "device": "pushover_devices",
836 "expire": "pushover_expire",
837 "message": "pushover_message",
838 "okPriority": "pushover_ok_priority",
839 "okSound": "pushover_ok_sound",
840 "priority": "pushover_priority",
841 "retry": "pushover_retry",
842 "sound": "pushover_sound",
843 "title": "pushover_title",
844 "uploadImage": "pushover_upload_image",
845 "userKey": "pushover_user_key",
846 },
847 "sensugo": {
848 "apiKey": "sensugo_api_key",
849 "url": "sensugo_url",
850 "check": "sensugo_check",
851 "entity": "sensugo_entity",
852 "handler": "sensugo_handler",
853 "message": "sensugo_message",
854 "namespace": "sensugo_namespace",
855 },
856 "slack": {
857 "endpointUrl": "slack_endpoint_url",
858 "icon_emoji": "slack_icon_emoji",
859 "icon_url": "slack_icon_url",
860 "mentionChannel": "slack_mention_channel",
861 "mentionGroups": "slack_mention_groups",
862 "mentionUsers": "slack_mention_users",
863 "recipient": "slack_recipient",
864 "text": "slack_text",
865 "title": "slack_title",
866 "token": "slack_token",
867 "url": "slack_url",
868 "username": "slack_username",
869 },
870 "teams": {
871 "message": "teams_message",
872 "sectiontitle": "teams_section_title",
873 "title": "teams_title",
874 "url": "teams_url",
875 },
876 "telegram": {
877 "chatid": "telegram_chat_id",
878 "disable_notification": "telegram_disable_notifications",
879 "message": "telegram_message",
880 "parse_mode": "telegram_parse_mode",
881 "protect_content": "telegram_protect_content",
882 "bottoken": "telegram_token",
883 "disable_web_page_preview": "telegram_web_page_view",
884 },
885 "threema": {
886 "api_secret": "threema_api_secret",
887 "description": "threema_description",
888 "gateway_id": "threema_gateway_id",
889 "recipient_id": "threema_recipient_id",
890 "title": "threema_title",
891 },
892 "victorops": {
893 "description": "victorops_description",
894 "messageType": "victorops_message_type",
895 "title": "victorops_title",
896 "url": "victorops_url",
897 },
898 "webex": {
899 "api_url": "webex_api_url",
900 "message": "webex_message",
901 "room_id": "webex_room_id",
902 "bot_token": "webex_token",
903 },
904 "webhook": {
905 "authorization_credentials": "webhook_authorization_credentials",
906 "authorization_scheme": "webhook_authorization_scheme",
907 "httpMethod": "webhook_http_method",
908 "maxAlerts": "webhook_max_alerts",
909 "message": "webhook_message",
910 "password": "webhook_password",
911 "title": "webhook_title",
912 "url": "webhook_url",
913 "username": "webhook_username",
914 },
915 "wecom": {
916 "agent_id": "wecom_agent_id",
917 "corp_id": "wecom_corp_id",
918 "message": "wecom_message",
919 "msgtype": "wecom_msg_type",
920 "secret": "wecom_secret",
921 "title": "wecom_title",
922 "touser": "wecom_to_user",
923 "url": "wecom_url",
924 },
925 }
926
927 type_settings = type_settings_map.get(data["type"])
928 if type_settings:
929 for setting_key, data_key in type_settings.items():
930 if data[data_key] is not None:
931 if data_key == "pushover_priority":
932 payload["settings"][setting_key] = {
933 "emergency": "2",
934 "high": "1",
935 "normal": "0",
936 "low": "-1",
937 "lowest": "-2",
938 }[data[data_key]]
939 elif data_key == "dingding_message_type":
940 payload["settings"][setting_key] = {
941 "link": "link",
942 "action_card": "actionCard",
943 }[data[data_key]]
944 elif data_key in ["email_addresses", "pushover_devices"]:
945 payload["settings"][setting_key] = ";".join(data[data_key])
946 elif data_key in ["slack_mention_users", "slack_mention_groups"]:
947 payload["settings"][setting_key] = ",".join(data[data_key])
948 elif data.get(data_key):
949 payload["settings"][setting_key] = data[data_key]
950
951 return payload
952
953
954 class GrafanaContactPointInterface(object):
955 def __init__(self, module):
956 self._module = module
957 self.org_id = None
958 # {{{ Authentication header
959 self.headers = {"Content-Type": "application/json"}
960 if module.params.get("grafana_api_key", None):
961 self.headers["Authorization"] = (
962 "Bearer %s" % module.params["grafana_api_key"]
963 )
964 else:
965 self.headers["Authorization"] = basic_auth_header(
966 module.params["url_username"], module.params["url_password"]
967 )
968 self.org_id = (
969 self.grafana_organization_by_name(
970 module.params, module.params["org_name"]
971 )
972 if module.params["org_name"]
973 else module.params["org_id"]
974 )
975 self.grafana_switch_organisation(module.params, self.org_id)
976 # }}}
977 self.contact_point = self.grafana_check_contact_point_match(module.params)
978
979 def grafana_handle_api_provisioning(self, data):
980 if not self.contact_point or (
981 not self.contact_point.get("provenance") and not data.get("provisioning")
982 ):
983 self.headers["X-Disable-Provenance"] = "true"
984 elif self.contact_point.get("provenance") and not data.get("provisioning"):
985 self._module.fail_json(
986 msg="Unable to update contact point '%s': provisioning cannot be disabled if it's already enabled"
987 % data["uid"]
988 )
989 else:
990 pass
991
992 def grafana_organization_by_name(self, data, org_name):
993 r, info = fetch_url(
994 self._module,
995 "%s/api/user/orgs" % data["url"],
996 headers=self.headers,
997 method="GET",
998 )
999 organizations = json.loads(to_text(r.read()))
1000 orga = next((org for org in organizations if org["name"] == org_name))
1001 if orga:
1002 return orga["orgId"]
1003
1004 raise GrafanaAPIException(
1005 "Current user isn't member of organization: %s" % org_name
1006 )
1007
1008 def grafana_switch_organisation(self, data, org_id):
1009 r, info = fetch_url(
1010 self._module,
1011 "%s/api/user/using/%s" % (data["url"], org_id),
1012 headers=self.headers,
1013 method="POST",
1014 )
1015 if info["status"] != 200:
1016 raise GrafanaAPIException(
1017 "Unable to switch to organization '%s': %s" % (org_id, info)
1018 )
1019
1020 def grafana_check_contact_point_match(self, data):
1021 r, info = fetch_url(
1022 self._module,
1023 "%s/api/v1/provisioning/contact-points" % data["url"],
1024 headers=self.headers,
1025 method="GET",
1026 )
1027
1028 if info["status"] == 200:
1029 contact_points = json.loads(to_text(r.read()))
1030 contact_point = next(
1031 (cp for cp in contact_points if cp["uid"] == data["uid"]), None
1032 )
1033 return contact_point
1034 elif info["status"] == 404:
1035 self._module.fail_json(
1036 msg="Unable to get contact point: API endpoint not found - please check your Grafana version"
1037 )
1038 else:
1039 raise GrafanaAPIException(
1040 "Unable to get contact point '%s': %s" % (data["uid"], info)
1041 )
1042
1043 def grafana_handle_contact_point(self, data):
1044 payload = grafana_contact_point_payload(data)
1045
1046 if data["state"] == "present":
1047 self.grafana_handle_api_provisioning(data)
1048 if self.contact_point:
1049 return self.grafana_update_contact_point(data, payload)
1050 else:
1051 return self.grafana_create_contact_point(data, payload)
1052 else:
1053 if self.contact_point:
1054 return self.grafana_delete_contact_point(data)
1055 else:
1056 return {"changed": False, "state": data["state"]}
1057
1058 def grafana_create_contact_point(self, data, payload):
1059 r, info = fetch_url(
1060 self._module,
1061 "%s/api/v1/provisioning/contact-points" % data["url"],
1062 data=json.dumps(payload),
1063 headers=self.headers,
1064 method="POST",
1065 )
1066
1067 if info["status"] == 202:
1068 contact_point = json.loads(to_text(r.read()))
1069 return {
1070 "changed": True,
1071 "contact_point": contact_point,
1072 "state": data["state"],
1073 }
1074 else:
1075 raise GrafanaAPIException("Unable to create contact point: %s" % info)
1076
1077 def grafana_update_contact_point(self, data, payload):
1078 r, info = fetch_url(
1079 self._module,
1080 "%s/api/v1/provisioning/contact-points/%s" % (data["url"], data["uid"]),
1081 data=json.dumps(payload),
1082 headers=self.headers,
1083 method="PUT",
1084 )
1085
1086 if info["status"] == 202:
1087 contact_point = self.grafana_check_contact_point_match(data)
1088
1089 if contact_point.get("provenance") and data.get("provisioning"):
1090 del contact_point["provenance"]
1091
1092 if self.contact_point == contact_point:
1093 return {
1094 "changed": False,
1095 "contact_point": contact_point,
1096 "state": data["state"],
1097 }
1098 else:
1099 return {
1100 "changed": True,
1101 "diff": {"before": self.contact_point, "after": contact_point},
1102 "contact_point": contact_point,
1103 "state": data["state"],
1104 }
1105 else:
1106 raise GrafanaAPIException(
1107 "Unable to update contact point '%s': %s" % (data["uid"], info)
1108 )
1109
1110 def grafana_delete_contact_point(self, data):
1111 r, info = fetch_url(
1112 self._module,
1113 "%s/api/v1/provisioning/contact-points/%s" % (data["url"], data["uid"]),
1114 headers=self.headers,
1115 method="DELETE",
1116 )
1117
1118 if info["status"] == 202:
1119 return {
1120 "changed": True,
1121 "contact_point": self.contact_point,
1122 "state": data["state"],
1123 }
1124 elif info["status"] == 404:
1125 return {"changed": False, "state": data["state"]}
1126 else:
1127 raise GrafanaAPIException(
1128 "Unable to delete contact point '%s': %s" % (data["uid"], info)
1129 )
1130
1131
1132 def main():
1133 argument_spec = grafana_argument_spec()
1134 argument_spec.update(
1135 # general arguments
1136 disable_resolve_message=dict(type="bool", default=False),
1137 include_image=dict(type="bool", default=False),
1138 name=dict(type="str"),
1139 org_id=dict(type="int", default=1),
1140 org_name=dict(type="str"),
1141 provisioning=dict(type="bool", default=True),
1142 type=dict(
1143 type="str",
1144 choices=[
1145 "alertmanager",
1146 "dingding",
1147 "discord",
1148 "email",
1149 "googlechat",
1150 "kafka",
1151 "line",
1152 "opsgenie",
1153 "pagerduty",
1154 "pushover",
1155 "sensugo",
1156 "slack",
1157 "teams",
1158 "telegram",
1159 "threema",
1160 "victorops",
1161 "webex",
1162 "webhook",
1163 "wecom",
1164 ],
1165 ),
1166 uid=dict(required=True, type="str"),
1167 # alertmanager
1168 alertmanager_password=dict(type="str", no_log=True),
1169 alertmanager_url=dict(type="str"),
1170 alertmanager_username=dict(type="str"),
1171 # dingding
1172 dingding_message=dict(type="str"),
1173 dingding_message_type=dict(type="str"),
1174 dingding_title=dict(type="str"),
1175 dingding_url=dict(type="str"),
1176 # discord
1177 discord_avatar_url=dict(type="str"),
1178 discord_message=dict(type="str"),
1179 discord_title=dict(type="str"),
1180 discord_url=dict(type="str", no_log=True),
1181 discord_use_username=dict(type="bool", default=False),
1182 # email
1183 email_addresses=dict(type="list", elements="str"),
1184 email_message=dict(type="str"),
1185 email_single=dict(type="bool", default=False),
1186 email_subject=dict(type="str"),
1187 # googlechat
1188 googlechat_url=dict(type="str", no_log=True),
1189 googlechat_message=dict(type="str"),
1190 googlechat_title=dict(type="str"),
1191 # kafka
1192 kafka_api_version=dict(type="str", default="v2"),
1193 kafka_cluster_id=dict(type="str"),
1194 kafka_description=dict(type="str"),
1195 kafka_details=dict(type="str"),
1196 kafka_password=dict(type="str", no_log=True),
1197 kafka_rest_proxy_url=dict(type="str", no_log=True),
1198 kafka_topic=dict(type="str"),
1199 kafka_username=dict(type="str"),
1200 # line
1201 line_description=dict(type="str"),
1202 line_title=dict(type="str"),
1203 line_token=dict(type="str", no_log=True),
1204 # opsgenie
1205 opsgenie_api_key=dict(type="str", no_log=True),
1206 opsgenie_auto_close=dict(type="bool"),
1207 opsgenie_description=dict(type="str"),
1208 opsgenie_message=dict(type="str"),
1209 opsgenie_override_priority=dict(type="bool"),
1210 opsgenie_responders=dict(type="list", elements="dict"),
1211 opsgenie_send_tags_as=dict(type="str"),
1212 opsgenie_url=dict(type="str"),
1213 # pagerduty
1214 pagerduty_class=dict(type="str"),
1215 pagerduty_client=dict(type="str"),
1216 pagerduty_client_url=dict(type="str"),
1217 pagerduty_component=dict(type="str"),
1218 pagerduty_details=dict(type="list", elements="dict"),
1219 pagerduty_group=dict(type="str"),
1220 pagerduty_integration_key=dict(type="str", no_log=True),
1221 pagerduty_severity=dict(
1222 type="str", choices=["critical", "error", "warning", "info"]
1223 ),
1224 pagerduty_source=dict(type="str"),
1225 pagerduty_summary=dict(type="str"),
1226 # pushover
1227 pushover_api_token=dict(type="str", no_log=True),
1228 pushover_devices=dict(type="list", elements="str"),
1229 pushover_expire=dict(type="int"),
1230 pushover_message=dict(type="str"),
1231 pushover_ok_priority=dict(type="int"),
1232 pushover_ok_sound=dict(type="str"),
1233 pushover_priority=dict(type="int"),
1234 pushover_retry=dict(type="int"),
1235 pushover_sound=dict(type="str"),
1236 pushover_title=dict(type="str"),
1237 pushover_upload_image=dict(type="bool", default=True),
1238 pushover_user_key=dict(type="str", no_log=True),
1239 # sensugo
1240 sensugo_api_key=dict(type="str", no_log=True),
1241 sensugo_url=dict(type="str"),
1242 sensugo_check=dict(type="str"),
1243 sensugo_entity=dict(type="str"),
1244 sensugo_handler=dict(type="str"),
1245 sensugo_message=dict(type="str"),
1246 sensugo_namespace=dict(type="str"),
1247 # slack
1248 slack_endpoint_url=dict(type="str"),
1249 slack_icon_emoji=dict(type="str"),
1250 slack_icon_url=dict(type="str"),
1251 slack_mention_channel=dict(type="str", choices=["here", "channel"]),
1252 slack_mention_groups=dict(type="list", elements="str"),
1253 slack_mention_users=dict(type="list", elements="str"),
1254 slack_recipient=dict(type="str"),
1255 slack_text=dict(type="str"),
1256 slack_title=dict(type="str"),
1257 slack_token=dict(type="str", no_log=True),
1258 slack_url=dict(type="str", no_log=True),
1259 slack_username=dict(type="str"),
1260 # teams
1261 teams_message=dict(type="str"),
1262 teams_section_title=dict(type="str"),
1263 teams_title=dict(type="str"),
1264 teams_url=dict(type="str", no_log=True),
1265 # telegram
1266 telegram_chat_id=dict(type="str"),
1267 telegram_disable_notifications=dict(type="bool"),
1268 telegram_message=dict(type="str"),
1269 telegram_parse_mode=dict(type="str"),
1270 telegram_protect_content=dict(type="bool"),
1271 telegram_token=dict(type="str", no_log=True),
1272 telegram_web_page_view=dict(type="bool"),
1273 # threema
1274 threema_api_secret=dict(type="str", no_log=True),
1275 threema_description=dict(type="str"),
1276 threema_gateway_id=dict(type="str"),
1277 threema_recipient_id=dict(type="str"),
1278 threema_title=dict(type="str"),
1279 # victorops
1280 victorops_description=dict(type="str"),
1281 victorops_message_type=dict(type="str", choices=["CRITICAL", "RECOVERY"]),
1282 victorops_title=dict(type="str"),
1283 victorops_url=dict(type="str"),
1284 # webex
1285 webex_api_url=dict(type="str"),
1286 webex_message=dict(type="str"),
1287 webex_room_id=dict(type="str"),
1288 webex_token=dict(type="str", no_log=True),
1289 # webhook
1290 webhook_authorization_credentials=dict(type="str", no_log=True),
1291 webhook_authorization_scheme=dict(type="str"),
1292 webhook_http_method=dict(type="str", choices=["POST", "PUT"]),
1293 webhook_max_alerts=dict(type="int"),
1294 webhook_message=dict(type="str"),
1295 webhook_password=dict(type="str", no_log=True),
1296 webhook_title=dict(type="str"),
1297 webhook_url=dict(type="str"),
1298 webhook_username=dict(type="str"),
1299 # wecom
1300 wecom_agent_id=dict(type="str"),
1301 wecom_corp_id=dict(type="str"),
1302 wecom_message=dict(type="str"),
1303 wecom_msg_type=dict(type="str"),
1304 wecom_secret=dict(type="str", no_log=True),
1305 wecom_title=dict(type="str"),
1306 wecom_to_user=dict(type="list", elements="str"),
1307 wecom_url=dict(type="str", no_log=True),
1308 )
1309
1310 module = AnsibleModule(
1311 argument_spec=argument_spec,
1312 supports_check_mode=False,
1313 required_together=[["url_username", "url_password", "org_id"]],
1314 mutually_exclusive=[["url_username", "grafana_api_key"]],
1315 required_if=[
1316 ["state", "present", ["name", "type"]],
1317 ["type", "alertmanager", ["alertmanager_url"]],
1318 ["type", "dingding", ["dingding_url"]],
1319 ["type", "discord", ["discord_url"]],
1320 ["type", "email", ["email_addresses"]],
1321 ["type", "googlechat", ["googlechat_url"]],
1322 ["type", "kafka", ["kafka_rest_proxy_url", "kafka_topic"]],
1323 ["type", "line", ["line_token"]],
1324 ["type", "opsgenie", ["opsgenie_api_key", "opsgenie_url"]],
1325 ["type", "pagerduty", ["pagerduty_integration_key"]],
1326 ["type", "pushover", ["pushover_api_token", "pushover_user_key"]],
1327 ["type", "sensugo", ["sensugo_api_key", "sensugo_url"]],
1328 ["type", "slack", ["slack_recipient", "slack_token", "slack_url"]],
1329 ["type", "teams", ["teams_url"]],
1330 ["type", "telegram", ["telegram_chat_id", "telegram_token"]],
1331 [
1332 "type",
1333 "threema",
1334 ["threema_api_secret", "threema_gateway_id", "threema_recipient_id"],
1335 ],
1336 ["type", "victorops", ["victorops_url"]],
1337 ["type", "webex", ["webex_token", "webex_room_id"]],
1338 ["type", "webhook", ["webhook_url"]],
1339 [
1340 "type",
1341 "wecom",
1342 ["wecom_url", "wecom_agent_id", "wecom_corp_id", "wecom_secret"],
1343 ],
1344 ],
1345 )
1346
1347 module.params["url"] = clean_url(module.params["url"])
1348 grafana_iface = GrafanaContactPointInterface(module)
1349
1350 result = grafana_iface.grafana_handle_contact_point(module.params)
1351 module.exit_json(failed=False, **result)
1352
1353
1354 if __name__ == "__main__":
1355 main()
1356 # TODO: check api messages