| 1 |
# Copyright (c) 2014-2015, Matt Martz <[email protected]> |
| 2 |
# Copyright (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
# Make coding more python3-ish |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
author: Unknown (!UNKNOWN) |
| 11 |
name: slack |
| 12 |
type: notification |
| 13 |
requirements: |
| 14 |
- whitelist in configuration |
| 15 |
- prettytable (python library) |
| 16 |
short_description: Sends play events to a Slack channel |
| 17 |
description: |
| 18 |
- This is an ansible callback plugin that sends status updates to a Slack channel during playbook execution. |
| 19 |
options: |
| 20 |
http_agent: |
| 21 |
description: |
| 22 |
- HTTP user agent to use for requests to Slack. |
| 23 |
type: string |
| 24 |
version_added: "10.5.0" |
| 25 |
webhook_url: |
| 26 |
required: true |
| 27 |
description: Slack Webhook URL. |
| 28 |
type: str |
| 29 |
env: |
| 30 |
- name: SLACK_WEBHOOK_URL |
| 31 |
ini: |
| 32 |
- section: callback_slack |
| 33 |
key: webhook_url |
| 34 |
channel: |
| 35 |
default: "#ansible" |
| 36 |
description: Slack room to post in. |
| 37 |
type: str |
| 38 |
env: |
| 39 |
- name: SLACK_CHANNEL |
| 40 |
ini: |
| 41 |
- section: callback_slack |
| 42 |
key: channel |
| 43 |
username: |
| 44 |
description: Username to post as. |
| 45 |
type: str |
| 46 |
env: |
| 47 |
- name: SLACK_USERNAME |
| 48 |
default: ansible |
| 49 |
ini: |
| 50 |
- section: callback_slack |
| 51 |
key: username |
| 52 |
validate_certs: |
| 53 |
description: Validate the SSL certificate of the Slack server for HTTPS URLs. |
| 54 |
env: |
| 55 |
- name: SLACK_VALIDATE_CERTS |
| 56 |
ini: |
| 57 |
- section: callback_slack |
| 58 |
key: validate_certs |
| 59 |
default: true |
| 60 |
type: bool |
| 61 |
""" |
| 62 |
|
| 63 |
import json |
| 64 |
import os |
| 65 |
import uuid |
| 66 |
|
| 67 |
from ansible import context |
| 68 |
from ansible.module_utils.urls import open_url |
| 69 |
from ansible.plugins.callback import CallbackBase |
| 70 |
|
| 71 |
try: |
| 72 |
import prettytable |
| 73 |
|
| 74 |
HAS_PRETTYTABLE = True |
| 75 |
except ImportError: |
| 76 |
HAS_PRETTYTABLE = False |
| 77 |
|
| 78 |
|
| 79 |
class CallbackModule(CallbackBase): |
| 80 |
"""This is an ansible callback plugin that sends status |
| 81 |
updates to a Slack channel during playbook execution. |
| 82 |
""" |
| 83 |
|
| 84 |
CALLBACK_VERSION = 2.0 |
| 85 |
CALLBACK_TYPE = "notification" |
| 86 |
CALLBACK_NAME = "community.general.slack" |
| 87 |
CALLBACK_NEEDS_WHITELIST = True |
| 88 |
|
| 89 |
def __init__(self, display=None): |
| 90 |
super().__init__(display=display) |
| 91 |
|
| 92 |
if not HAS_PRETTYTABLE: |
| 93 |
self.disabled = True |
| 94 |
self._display.warning( |
| 95 |
"The `prettytable` python module is not installed. Disabling the Slack callback plugin." |
| 96 |
) |
| 97 |
|
| 98 |
self.playbook_name = None |
| 99 |
|
| 100 |
# This is a 6 character identifier provided with each message |
| 101 |
# This makes it easier to correlate messages when there are more |
| 102 |
# than 1 simultaneous playbooks running |
| 103 |
self.guid = uuid.uuid4().hex[:6] |
| 104 |
|
| 105 |
def set_options(self, task_keys=None, var_options=None, direct=None): |
| 106 |
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct) |
| 107 |
|
| 108 |
self.webhook_url = self.get_option("webhook_url") |
| 109 |
self.channel = self.get_option("channel") |
| 110 |
self.username = self.get_option("username") |
| 111 |
self.show_invocation = self._display.verbosity > 1 |
| 112 |
self.validate_certs = self.get_option("validate_certs") |
| 113 |
self.http_agent = self.get_option("http_agent") |
| 114 |
if self.webhook_url is None: |
| 115 |
self.disabled = True |
| 116 |
self._display.warning( |
| 117 |
"Slack Webhook URL was not provided. The " |
| 118 |
"Slack Webhook URL can be provided using " |
| 119 |
"the `SLACK_WEBHOOK_URL` environment " |
| 120 |
"variable." |
| 121 |
) |
| 122 |
|
| 123 |
def send_msg(self, attachments): |
| 124 |
headers = { |
| 125 |
"Content-type": "application/json", |
| 126 |
} |
| 127 |
|
| 128 |
payload = { |
| 129 |
"channel": self.channel, |
| 130 |
"username": self.username, |
| 131 |
"attachments": attachments, |
| 132 |
"parse": "none", |
| 133 |
"icon_url": ("https://cdn2.hubspot.net/hub/330046/file-449187601-png/ansible_badge.png"), |
| 134 |
} |
| 135 |
|
| 136 |
data = json.dumps(payload) |
| 137 |
self._display.debug(data) |
| 138 |
self._display.debug(self.webhook_url) |
| 139 |
try: |
| 140 |
response = open_url( |
| 141 |
self.webhook_url, |
| 142 |
data=data, |
| 143 |
validate_certs=self.validate_certs, |
| 144 |
headers=headers, |
| 145 |
http_agent=self.http_agent, |
| 146 |
) |
| 147 |
return response.read() |
| 148 |
except Exception as e: |
| 149 |
self._display.warning(f"Could not submit message to Slack: {e}") |
| 150 |
|
| 151 |
def v2_playbook_on_start(self, playbook): |
| 152 |
self.playbook_name = os.path.basename(playbook._file_name) |
| 153 |
|
| 154 |
title = [f"*Playbook initiated* (_{self.guid}_)"] |
| 155 |
|
| 156 |
invocation_items = [] |
| 157 |
if context.CLIARGS and self.show_invocation: |
| 158 |
tags = context.CLIARGS["tags"] |
| 159 |
skip_tags = context.CLIARGS["skip_tags"] |
| 160 |
extra_vars = context.CLIARGS["extra_vars"] |
| 161 |
subset = context.CLIARGS["subset"] |
| 162 |
inventory = [os.path.abspath(i) for i in context.CLIARGS["inventory"]] |
| 163 |
|
| 164 |
invocation_items.append(f"Inventory: {', '.join(inventory)}") |
| 165 |
if tags and tags != ["all"]: |
| 166 |
invocation_items.append(f"Tags: {', '.join(tags)}") |
| 167 |
if skip_tags: |
| 168 |
invocation_items.append(f"Skip Tags: {', '.join(skip_tags)}") |
| 169 |
if subset: |
| 170 |
invocation_items.append(f"Limit: {subset}") |
| 171 |
if extra_vars: |
| 172 |
invocation_items.append(f"Extra Vars: {' '.join(extra_vars)}") |
| 173 |
|
| 174 |
title.append(f"by *{context.CLIARGS['remote_user']}*") |
| 175 |
|
| 176 |
title.append(f"\n\n*{self.playbook_name}*") |
| 177 |
msg_items = [" ".join(title)] |
| 178 |
if invocation_items: |
| 179 |
_inv_item = "\n".join(invocation_items) |
| 180 |
msg_items.append(f"```\n{_inv_item}\n```") |
| 181 |
|
| 182 |
msg = "\n".join(msg_items) |
| 183 |
|
| 184 |
attachments = [ |
| 185 |
{ |
| 186 |
"fallback": msg, |
| 187 |
"fields": [{"value": msg}], |
| 188 |
"color": "warning", |
| 189 |
"mrkdwn_in": ["text", "fallback", "fields"], |
| 190 |
} |
| 191 |
] |
| 192 |
|
| 193 |
self.send_msg(attachments=attachments) |
| 194 |
|
| 195 |
def v2_playbook_on_play_start(self, play): |
| 196 |
"""Display Play start messages""" |
| 197 |
|
| 198 |
name = play.name or f"Play name not specified ({play._uuid})" |
| 199 |
msg = f"*Starting play* (_{self.guid}_)\n\n*{name}*" |
| 200 |
attachments = [ |
| 201 |
{ |
| 202 |
"fallback": msg, |
| 203 |
"text": msg, |
| 204 |
"color": "warning", |
| 205 |
"mrkdwn_in": ["text", "fallback", "fields"], |
| 206 |
} |
| 207 |
] |
| 208 |
self.send_msg(attachments=attachments) |
| 209 |
|
| 210 |
def v2_playbook_on_stats(self, stats): |
| 211 |
"""Display info about playbook statistics""" |
| 212 |
|
| 213 |
hosts = sorted(stats.processed.keys()) |
| 214 |
|
| 215 |
t = prettytable.PrettyTable(["Host", "Ok", "Changed", "Unreachable", "Failures", "Rescued", "Ignored"]) |
| 216 |
|
| 217 |
failures = False |
| 218 |
unreachable = False |
| 219 |
|
| 220 |
for h in hosts: |
| 221 |
s = stats.summarize(h) |
| 222 |
|
| 223 |
if s["failures"] > 0: |
| 224 |
failures = True |
| 225 |
if s["unreachable"] > 0: |
| 226 |
unreachable = True |
| 227 |
|
| 228 |
t.add_row([h] + [s[k] for k in ["ok", "changed", "unreachable", "failures", "rescued", "ignored"]]) |
| 229 |
|
| 230 |
attachments = [] |
| 231 |
msg_items = [f"*Playbook Complete* (_{self.guid}_)"] |
| 232 |
if failures or unreachable: |
| 233 |
color = "danger" |
| 234 |
msg_items.append("\n*Failed!*") |
| 235 |
else: |
| 236 |
color = "good" |
| 237 |
msg_items.append("\n*Success!*") |
| 238 |
|
| 239 |
msg_items.append(f"```\n{t}\n```") |
| 240 |
|
| 241 |
msg = "\n".join(msg_items) |
| 242 |
|
| 243 |
attachments.append( |
| 244 |
{"fallback": msg, "fields": [{"value": msg}], "color": color, "mrkdwn_in": ["text", "fallback", "fields"]} |
| 245 |
) |
| 246 |
|
| 247 |
self.send_msg(attachments=attachments) |