Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, Lee Goolsbee <[email protected]>
4 # Copyright (c) 2020, Michal Middleton <[email protected]>
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: slack
17 short_description: Send Slack notifications
18 description:
19 - The M(community.general.slack) module sends notifications to U(http://slack.com) using the Incoming WebHook integration.
20 author: "Ramon de la Fuente (@ramondelafuente)"
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 domain:
30 type: str
31 description:
32 - "When using new format 'Webhook token' and WebAPI tokens: this can be V(slack.com) or V(slack-gov.com) and is ignored
33 otherwise."
34 - "When using old format 'Webhook token': Slack (sub)domain for your environment without protocol. (For example V(example.slack.com).)
35 in Ansible 1.8 and beyond, this is deprecated and may be ignored. See token documentation for information."
36 token:
37 type: str
38 description:
39 - Slack integration token. This authenticates you to the Slack service. Make sure to use the correct type of token,
40 depending on what method you use.
41 - 'Webhook token: Prior to Ansible 1.8, a token looked like V(3Ffe373sfhRE6y42Fg3rvf4GlK). In Ansible 1.8 and above,
42 Ansible adapts to the new Slack API where tokens look like V(G922VJP24/D921DW937/3Ffe373sfhRE6y42Fg3rvf4GlK). If tokens
43 are in the new format then Slack ignores any value of domain except V(slack.com) or V(slack-gov.com). If the token
44 is in the old format the domain is required. Ansible has no control of when Slack is going to remove the old API.
45 When Slack does that the old format is going to cease working. B(Please keep in mind the tokens are not the API tokens
46 but are the webhook tokens.) In Slack these are found in the webhook URL which are obtained under the apps and integrations.
47 The incoming webhooks can be added in that area. In some cases this may be locked by your Slack admin and you must
48 request access. It is there that the incoming webhooks can be added. The key is on the end of the URL given to you
49 in that section.'
50 - "WebAPI token: Slack WebAPI requires a personal, bot or work application token. These tokens start with V(xoxp-),
51 V(xoxb-) or V(xoxa-), for example V(xoxb-1234-56789abcdefghijklmnop). WebAPI token is required if you intend to receive
52 thread_id. See Slack's documentation (U(https://api.slack.com/docs/token-types)) for more information."
53 required: true
54 msg:
55 type: str
56 description:
57 - Message to send. Note that the module does not handle escaping characters. Plain-text angle brackets and ampersands
58 should be converted to HTML entities (for example C(&) to C(&amp;)) before sending. See Slack's documentation
59 (U(https://api.slack.com/docs/message-formatting))
60 for more.
61 channel:
62 type: str
63 description:
64 - Channel to send the message to. If absent, the message goes to the channel selected for the O(token).
65 thread_id:
66 description:
67 - Optional. Timestamp of parent message to thread this message, see U(https://api.slack.com/docs/message-threading).
68 type: str
69 message_id:
70 description:
71 - Optional. Message ID to edit, instead of posting a new message.
72 - If supplied O(channel) must be in form of C(C0xxxxxxx). use C({{ slack_response.channel }}) to get RV(ignore:channel)
73 from previous task run.
74 - The token needs history scope to get information on the message to edit (C(channels:history,groups:history,mpim:history,im:history)).
75 - Corresponds to C(ts) in the Slack API (U(https://api.slack.com/messaging/modifying)).
76 type: str
77 version_added: 1.2.0
78 username:
79 type: str
80 description:
81 - This is the sender of the message.
82 default: "Ansible"
83 icon_url:
84 type: str
85 description:
86 - URL for the message sender's icon.
87 default: https://docs.ansible.com/favicon/favicon.ico
88 icon_emoji:
89 type: str
90 description:
91 - Emoji for the message sender. See Slack documentation for options.
92 - If O(icon_emoji) is set, O(icon_url) is not used.
93 link_names:
94 type: int
95 description:
96 - Automatically create links for channels and usernames in O(msg).
97 default: 1
98 choices:
99 - 1
100 - 0
101 parse:
102 type: str
103 description:
104 - Setting for the message parser at Slack.
105 choices:
106 - 'full'
107 - 'none'
108 validate_certs:
109 description:
110 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
111 certificates.
112 type: bool
113 default: true
114 color:
115 type: str
116 description:
117 - Allow text to use default colors - use the default of V(normal) to not send a custom color bar at the start of the
118 message.
119 - Allowed values for color can be one of V(normal), V(good), V(warning), V(danger), any valid 3 digit or 6 digit hex
120 color value.
121 default: 'normal'
122 attachments:
123 type: list
124 elements: dict
125 description:
126 - Define a list of attachments. This list mirrors the Slack JSON API.
127 - For more information, see U(https://api.slack.com/docs/attachments).
128 blocks:
129 description:
130 - Define a list of blocks. This list mirrors the Slack JSON API.
131 - For more information, see U(https://api.slack.com/block-kit).
132 type: list
133 elements: dict
134 version_added: 1.0.0
135 prepend_hash:
136 type: str
137 description:
138 - Setting for automatically prepending a V(#) symbol on the passed in O(channel).
139 - The V(auto) method prepends a V(#) unless O(channel) starts with one of V(#), V(@), V(C0), V(GF), V(G0), V(CP). These
140 prefixes only cover a small set of the prefixes that should not have a V(#) prepended. Since an exact condition which
141 O(channel) values must not have the V(#) prefix is not known, the value V(auto) for this option is deprecated in the
142 future. It is best to explicitly set O(prepend_hash=always) or O(prepend_hash=never) to obtain the needed behavior.
143 - Before community.general 12.0.0, the default was V(auto). It has been deprecated since community.general 10.2.0.
144 - Note that V(auto) will be deprecated in a future version.
145 # TODO: Deprecate 'auto' in community.general 13.0.0
146 default: never
147 choices:
148 - 'always'
149 - 'never'
150 - 'auto'
151 version_added: 6.1.0
152 """
153
154 EXAMPLES = r"""
155 - name: Send notification message via Slack
156 community.general.slack:
157 token: thetoken/generatedby/slack
158 msg: '{{ inventory_hostname }} completed'
159 delegate_to: localhost
160
161 - name: Send notification message via Slack all options
162 community.general.slack:
163 token: thetoken/generatedby/slack
164 msg: '{{ inventory_hostname }} completed'
165 channel: '#ansible'
166 thread_id: '1539917263.000100'
167 username: 'Ansible on {{ inventory_hostname }}'
168 icon_url: http://www.example.com/some-image-file.png
169 link_names: 0
170 parse: 'none'
171 delegate_to: localhost
172
173 - name: Insert a color bar in front of the message for visibility purposes and use the default webhook icon and name configured
174 in Slack
175 community.general.slack:
176 token: thetoken/generatedby/slack
177 msg: '{{ inventory_hostname }} is alive!'
178 color: good
179 username: ''
180 icon_url: ''
181
182 - name: Insert a color bar in front of the message with valid hex color value
183 community.general.slack:
184 token: thetoken/generatedby/slack
185 msg: 'This message uses color in hex value'
186 color: '#00aacc'
187 username: ''
188 icon_url: ''
189
190 - name: Use the attachments API
191 community.general.slack:
192 token: thetoken/generatedby/slack
193 attachments:
194 - text: Display my system load on host A and B
195 color: '#ff00dd'
196 title: System load
197 fields:
198 - title: System A
199 value: "load average: 0,74, 0,66, 0,63"
200 short: true
201 - title: System B
202 value: 'load average: 5,16, 4,64, 2,43'
203 short: true
204
205 - name: Use the blocks API
206 community.general.slack:
207 token: thetoken/generatedby/slack
208 blocks:
209 - type: section
210 text:
211 type: mrkdwn
212 text: |-
213 *System load*
214 Display my system load on host A and B
215 - type: context
216 elements:
217 - type: mrkdwn
218 text: |-
219 *System A*
220 load average: 0,74, 0,66, 0,63
221 - type: mrkdwn
222 text: |-
223 *System B*
224 load average: 5,16, 4,64, 2,43
225
226 - name: Send a message with a link using Slack markup
227 community.general.slack:
228 token: thetoken/generatedby/slack
229 msg: We sent this message using <https://www.ansible.com|Ansible>!
230
231 - name: Send a message with angle brackets and ampersands
232 community.general.slack:
233 token: thetoken/generatedby/slack
234 msg: This message has &lt;brackets&gt; &amp; ampersands in plain text.
235
236 - name: Initial Threaded Slack message
237 community.general.slack:
238 channel: '#ansible'
239 token: xoxb-1234-56789abcdefghijklmnop
240 msg: 'Starting a thread with my initial post.'
241 register: slack_response
242 - name: Add more info to thread
243 community.general.slack:
244 channel: '#ansible'
245 token: xoxb-1234-56789abcdefghijklmnop
246 thread_id: "{{ slack_response['ts'] }}"
247 color: good
248 msg: 'And this is my threaded response!'
249
250 - name: Send a message to be edited later on
251 community.general.slack:
252 token: thetoken/generatedby/slack
253 channel: '#ansible'
254 msg: Deploying something...
255 register: slack_response
256 - name: Edit message
257 community.general.slack:
258 token: thetoken/generatedby/slack
259 # The 'channel' option does not accept the channel name. It must use the 'channel_id',
260 # which can be retrieved for example from 'slack_response' from the previous task.
261 channel: "{{ slack_response.channel }}"
262 msg: Deployment complete!
263 message_id: "{{ slack_response.ts }}"
264 """
265
266 import re
267 from urllib.parse import urlencode
268
269 from ansible.module_utils.basic import AnsibleModule
270 from ansible.module_utils.urls import fetch_url
271
272 # Escaping quotes and apostrophes to avoid ending string prematurely in ansible call.
273 # We do not escape other characters used as Slack metacharacters (e.g. &, <, >).
274 escape_table = {
275 '"': '"',
276 "'": "'",
277 }
278
279
280 def is_valid_hex_color(color_choice):
281 return bool(re.match(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", color_choice))
282
283
284 def escape_quotes(text):
285 """Backslash any quotes within text."""
286 return "".join(escape_table.get(c, c) for c in text)
287
288
289 def recursive_escape_quotes(obj, keys):
290 """Recursively escape quotes inside supplied keys inside block kit objects"""
291 if isinstance(obj, dict):
292 escaped = {}
293 for k, v in obj.items():
294 if isinstance(v, str) and k in keys:
295 escaped[k] = escape_quotes(v)
296 else:
297 escaped[k] = recursive_escape_quotes(v, keys)
298 elif isinstance(obj, list):
299 escaped = [recursive_escape_quotes(v, keys) for v in obj]
300 else:
301 escaped = obj
302 return escaped
303
304
305 def build_payload_for_slack(
306 text,
307 channel,
308 thread_id,
309 username,
310 icon_url,
311 icon_emoji,
312 link_names,
313 parse,
314 color,
315 attachments,
316 blocks,
317 message_id,
318 prepend_hash,
319 ):
320 payload = {}
321 if color == "normal" and text is not None:
322 payload = dict(text=escape_quotes(text))
323 elif text is not None:
324 # With a custom color we have to set the message as attachment, and explicitly turn markdown parsing on for it.
325 payload = dict(attachments=[dict(text=escape_quotes(text), color=color, mrkdwn_in=["text"])])
326 if channel is not None:
327 if prepend_hash == "auto":
328 if channel.startswith(("#", "@", "C0", "GF", "G0", "CP")):
329 payload["channel"] = channel
330 else:
331 payload["channel"] = f"#{channel}"
332 elif prepend_hash == "always":
333 payload["channel"] = f"#{channel}"
334 elif prepend_hash == "never":
335 payload["channel"] = channel
336 if thread_id is not None:
337 payload["thread_ts"] = thread_id
338 if username is not None:
339 payload["username"] = username
340 if icon_emoji is not None:
341 payload["icon_emoji"] = icon_emoji
342 else:
343 payload["icon_url"] = icon_url
344 if link_names is not None:
345 payload["link_names"] = link_names
346 if parse is not None:
347 payload["parse"] = parse
348 if message_id is not None:
349 payload["ts"] = message_id
350
351 if attachments is not None:
352 if "attachments" not in payload:
353 payload["attachments"] = []
354
355 if attachments is not None:
356 attachment_keys_to_escape = [
357 "title",
358 "text",
359 "author_name",
360 "pretext",
361 "fallback",
362 ]
363 for attachment in attachments:
364 for key in attachment_keys_to_escape:
365 if key in attachment:
366 attachment[key] = escape_quotes(attachment[key])
367
368 if "fallback" not in attachment:
369 attachment["fallback"] = attachment["text"]
370
371 payload["attachments"].append(attachment)
372
373 if blocks is not None:
374 block_keys_to_escape = ["text", "alt_text"]
375 payload["blocks"] = recursive_escape_quotes(blocks, block_keys_to_escape)
376
377 return payload
378
379
380 def validate_slack_domain(domain):
381 return domain if domain in ("slack.com", "slack-gov.com") else "slack.com"
382
383
384 def get_slack_message(module, domain, token, channel, ts):
385 headers = {
386 "Content-Type": "application/json; charset=UTF-8",
387 "Accept": "application/json",
388 "Authorization": f"Bearer {token}",
389 }
390 qs = urlencode(
391 {
392 "channel": channel,
393 "ts": ts,
394 "limit": 1,
395 "inclusive": "true",
396 }
397 )
398 domain = validate_slack_domain(domain)
399 url = f"https://{domain}/api/conversations.history?{qs}"
400 response, info = fetch_url(module=module, url=url, headers=headers, method="GET")
401 if info["status"] != 200:
402 module.fail_json(msg="failed to get slack message")
403 data = module.from_json(response.read())
404 if data.get("ok") is False:
405 module.fail_json(msg=f"failed to get slack message: {data}")
406 if len(data["messages"]) < 1:
407 module.fail_json(msg=f"no messages matching ts: {ts}")
408 if len(data["messages"]) > 1:
409 module.fail_json(msg=f"more than 1 message matching ts: {ts}")
410 return data["messages"][0]
411
412
413 def do_notify_slack(module, domain, token, payload):
414 use_webapi = False
415 if token.count("/") >= 2:
416 # New style webhook token
417 domain = validate_slack_domain(domain)
418 slack_uri = f"https://hooks.{domain}/services/{token}"
419 elif re.match(r"^xox[abp]-\S+$", token):
420 domain = validate_slack_domain(domain)
421 slack_uri = f"https://{domain}/api/{'chat.update' if 'ts' in payload else 'chat.postMessage'}"
422 use_webapi = True
423 else:
424 if not domain:
425 module.fail_json(
426 msg="Slack has updated its webhook API. You need to specify a token of the form "
427 "XXXX/YYYY/ZZZZ in your playbook"
428 )
429 slack_uri = f"https://{domain}/services/hooks/incoming-webhook?token={token}"
430
431 headers = {
432 "Content-Type": "application/json; charset=UTF-8",
433 "Accept": "application/json",
434 }
435 if use_webapi:
436 headers["Authorization"] = f"Bearer {token}"
437
438 data = module.jsonify(payload)
439 response, info = fetch_url(module=module, url=slack_uri, headers=headers, method="POST", data=data)
440
441 if info["status"] != 200:
442 if use_webapi:
443 obscured_incoming_webhook = slack_uri
444 else:
445 obscured_incoming_webhook = f"https://hooks.{domain}/services/[obscured]"
446 module.fail_json(msg=f" failed to send {data} to {obscured_incoming_webhook}: {info['msg']}")
447
448 # each API requires different handling
449 if use_webapi:
450 return module.from_json(response.read())
451 else:
452 return {"webhook": "ok"}
453
454
455 def main():
456 module = AnsibleModule(
457 argument_spec=dict(
458 domain=dict(type="str"),
459 token=dict(type="str", required=True, no_log=True),
460 msg=dict(type="str"),
461 channel=dict(type="str"),
462 thread_id=dict(type="str"),
463 username=dict(type="str", default="Ansible"),
464 icon_url=dict(type="str", default="https://docs.ansible.com/favicon/favicon.ico"),
465 icon_emoji=dict(type="str"),
466 link_names=dict(type="int", default=1, choices=[0, 1]),
467 parse=dict(type="str", choices=["none", "full"]),
468 validate_certs=dict(default=True, type="bool"),
469 color=dict(type="str", default="normal"),
470 attachments=dict(type="list", elements="dict"),
471 blocks=dict(type="list", elements="dict"),
472 message_id=dict(type="str"),
473 prepend_hash=dict(type="str", choices=["always", "never", "auto"], default="never"),
474 ),
475 supports_check_mode=True,
476 )
477
478 domain = module.params["domain"]
479 token = module.params["token"]
480 text = module.params["msg"]
481 channel = module.params["channel"]
482 thread_id = module.params["thread_id"]
483 username = module.params["username"]
484 icon_url = module.params["icon_url"]
485 icon_emoji = module.params["icon_emoji"]
486 link_names = module.params["link_names"]
487 parse = module.params["parse"]
488 color = module.params["color"]
489 attachments = module.params["attachments"]
490 blocks = module.params["blocks"]
491 message_id = module.params["message_id"]
492 prepend_hash = module.params["prepend_hash"]
493
494 color_choices = ["normal", "good", "warning", "danger"]
495 if color not in color_choices and not is_valid_hex_color(color):
496 module.fail_json(
497 msg=f"Color value specified should be either one of {color_choices} or any valid hex value with length 3 or 6."
498 )
499
500 changed = True
501
502 # if updating an existing message, we can check if there's anything to update
503 if message_id is not None:
504 changed = False
505 msg = get_slack_message(module, domain, token, channel, message_id)
506 for key in ("icon_url", "icon_emoji", "link_names", "color", "attachments", "blocks"):
507 if msg.get(key) != module.params.get(key):
508 changed = True
509 break
510 # if check mode is active, we shouldn't do anything regardless.
511 # if changed=False, we don't need to do anything, so don't do it.
512 if module.check_mode or not changed:
513 module.exit_json(changed=changed, ts=msg["ts"], channel=msg["channel"])
514 elif module.check_mode:
515 module.exit_json(changed=changed)
516
517 payload = build_payload_for_slack(
518 text,
519 channel,
520 thread_id,
521 username,
522 icon_url,
523 icon_emoji,
524 link_names,
525 parse,
526 color,
527 attachments,
528 blocks,
529 message_id,
530 prepend_hash,
531 )
532 slack_response = do_notify_slack(module, domain, token, payload)
533
534 if "ok" in slack_response:
535 # Evaluate WebAPI response
536 if slack_response["ok"]:
537 # return payload as a string for backwards compatibility
538 payload_json = module.jsonify(payload)
539 module.exit_json(
540 changed=changed,
541 ts=slack_response["ts"],
542 channel=slack_response["channel"],
543 api=slack_response,
544 payload=payload_json,
545 )
546 else:
547 module.fail_json(msg="Slack API error", error=slack_response["error"])
548 else:
549 # Exit with plain OK from WebHook, since we don't have more information
550 # If we get 200 from webhook, the only answer is OK
551 module.exit_json(msg="OK")
552
553
554 if __name__ == "__main__":
555 main()