Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) Benjamin Jolivot <[email protected]>
4 # Inspired by slack module :
5 # # Copyright (c) 2017, Steve Pletcher <[email protected]>
6 # # Copyright (c) 2016, René Moser <[email protected]>
7 # # Copyright (c) 2015, Stefan Berggren <[email protected]>
8 # # Copyright (c) 2014, Ramon de la Fuente <[email protected]>)
9 #
10 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
11 # SPDX-License-Identifier: GPL-3.0-or-later
12
13 from __future__ import annotations
14
15 DOCUMENTATION = r"""
16 module: mattermost
17 short_description: Send Mattermost notifications
18 description:
19 - Sends notifications to U(http://your.mattermost.url) using the Incoming WebHook integration.
20 author: "Benjamin Jolivot (@bjolivot)"
21 extends_documentation_fragment:
22 - community.general._attributes
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: none
28 options:
29 url:
30 type: str
31 description:
32 - Mattermost URL (for example V(http://mattermost.yourcompany.com)).
33 required: true
34 api_key:
35 type: str
36 description:
37 - Mattermost webhook API key. Log into your Mattermost site, go to Menu -> Integration -> Incoming Webhook -> Add Incoming
38 Webhook. This gives you a full URL. O(api_key) is the last part. U(http://mattermost.example.com/hooks/API_KEY).
39 required: true
40 text:
41 type: str
42 description:
43 - Text to send. Note that the module does not handle escaping characters.
44 - Required when O(attachments) is not set.
45 attachments:
46 type: list
47 elements: dict
48 description:
49 - Define a list of attachments.
50 - For more information, see U(https://developers.mattermost.com/integrate/admin-guide/admin-message-attachments/).
51 - Required when O(text) is not set.
52 version_added: 4.3.0
53 channel:
54 type: str
55 description:
56 - Channel to send the message to. If absent, the message goes to the channel selected for the O(api_key).
57 username:
58 type: str
59 description:
60 - This is the sender of the message (Username Override need to be enabled by mattermost admin, see mattermost doc).
61 default: Ansible
62 icon_url:
63 type: str
64 description:
65 - URL for the message sender's icon.
66 default: https://docs.ansible.com/favicon/favicon.ico
67 priority:
68 type: str
69 description:
70 - Set a priority for the message.
71 choices: [important, urgent]
72 version_added: 10.0.0
73 validate_certs:
74 description:
75 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
76 certificates.
77 default: true
78 type: bool
79 """
80
81 EXAMPLES = r"""
82 - name: Send notification message via Mattermost
83 community.general.mattermost:
84 url: http://mattermost.example.com
85 api_key: my_api_key
86 text: '{{ inventory_hostname }} completed'
87
88 - name: Send notification message via Mattermost all options
89 community.general.mattermost:
90 url: http://mattermost.example.com
91 api_key: my_api_key
92 text: '{{ inventory_hostname }} completed'
93 channel: notifications
94 username: 'Ansible on {{ inventory_hostname }}'
95 icon_url: http://www.example.com/some-image-file.png
96 priority: important
97
98 - name: Send attachments message via Mattermost
99 community.general.mattermost:
100 url: http://mattermost.example.com
101 api_key: my_api_key
102 attachments:
103 - text: Display my system load on host A and B
104 color: '#ff00dd'
105 title: System load
106 fields:
107 - title: System A
108 value: "load average: 0,74, 0,66, 0,63"
109 short: true
110 - title: System B
111 value: 'load average: 5,16, 4,64, 2,43'
112 short: true
113 """
114
115 RETURN = r"""
116 payload:
117 description: Mattermost payload.
118 returned: success
119 type: str
120 webhook_url:
121 description: URL the webhook is sent to.
122 returned: success
123 type: str
124 """
125
126 from ansible.module_utils.basic import AnsibleModule
127 from ansible.module_utils.urls import fetch_url
128
129
130 def main():
131 module = AnsibleModule(
132 supports_check_mode=True,
133 argument_spec=dict(
134 url=dict(type="str", required=True),
135 api_key=dict(type="str", required=True, no_log=True),
136 text=dict(type="str"),
137 channel=dict(type="str"),
138 username=dict(type="str", default="Ansible"),
139 icon_url=dict(type="str", default="https://docs.ansible.com/favicon/favicon.ico"),
140 priority=dict(type="str", choices=["important", "urgent"]),
141 validate_certs=dict(default=True, type="bool"),
142 attachments=dict(type="list", elements="dict"),
143 ),
144 required_one_of=[
145 ("text", "attachments"),
146 ],
147 )
148 # init return dict
149 result = dict(changed=False, msg="OK")
150
151 # define webhook
152 webhook_url = f"{module.params['url']}/hooks/{module.params['api_key']}"
153 result["webhook_url"] = webhook_url
154
155 # define payload
156 payload = {}
157 for param in ["text", "channel", "username", "icon_url", "attachments"]:
158 if module.params[param] is not None:
159 payload[param] = module.params[param]
160 if module.params["priority"] is not None:
161 payload["priority"] = {"priority": module.params["priority"]}
162
163 payload = module.jsonify(payload)
164 result["payload"] = payload
165
166 # http headers
167 headers = {
168 "Content-Type": "application/json",
169 "Accept": "application/json",
170 }
171
172 # notes:
173 # Nothing is done in check mode
174 # it'll pass even if your server is down or/and if your token is invalid.
175 # If someone find good way to check...
176
177 # send request if not in test mode
178 if module.check_mode is False:
179 response, info = fetch_url(module=module, url=webhook_url, headers=headers, method="POST", data=payload)
180
181 # something's wrong
182 if info["status"] != 200:
183 # some problem
184 result["msg"] = f"Failed to send mattermost message, the error was: {info['msg']}"
185 module.fail_json(**result)
186
187 # Looks good
188 module.exit_json(**result)
189
190
191 if __name__ == "__main__":
192 main()