Debian Codegraph @

ansible_collections/community/general/plugins/callback/mail.py

raw
1 # Copyright (c) 2012, Dag Wieers <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: mail
9 type: notification
10 short_description: Sends failure events through email
11 description:
12 - This callback reports failures through email.
13 author:
14 - Dag Wieers (@dagwieers)
15 requirements:
16 - whitelisting in configuration
17 options:
18 mta:
19 description:
20 - Mail Transfer Agent, server that accepts SMTP.
21 type: str
22 env:
23 - name: SMTPHOST
24 ini:
25 - section: callback_mail
26 key: smtphost
27 default: localhost
28 mtaport:
29 description:
30 - Mail Transfer Agent Port.
31 - Port at which server SMTP.
32 type: int
33 ini:
34 - section: callback_mail
35 key: smtpport
36 default: 25
37 to:
38 description:
39 - Mail recipient.
40 type: list
41 elements: str
42 ini:
43 - section: callback_mail
44 key: to
45 default: [root]
46 sender:
47 description:
48 - Mail sender.
49 - This is required since community.general 6.0.0.
50 type: str
51 required: true
52 ini:
53 - section: callback_mail
54 key: sender
55 cc:
56 description:
57 - CC'd recipients.
58 type: list
59 elements: str
60 ini:
61 - section: callback_mail
62 key: cc
63 bcc:
64 description:
65 - BCC'd recipients.
66 type: list
67 elements: str
68 ini:
69 - section: callback_mail
70 key: bcc
71 message_id_domain:
72 description:
73 - The domain name to use for the L(Message-ID header, https://en.wikipedia.org/wiki/Message-ID).
74 - The default is the hostname of the control node.
75 type: str
76 ini:
77 - section: callback_mail
78 key: message_id_domain
79 version_added: 8.2.0
80 """
81
82 import email.utils
83 import json
84 import os
85 import re
86 import smtplib
87
88 from ansible.module_utils.common.text.converters import to_bytes
89 from ansible.parsing.ajson import AnsibleJSONEncoder
90 from ansible.plugins.callback import CallbackBase
91
92
93 class CallbackModule(CallbackBase):
94 """This Ansible callback plugin mails errors to interested parties."""
95
96 CALLBACK_VERSION = 2.0
97 CALLBACK_TYPE = "notification"
98 CALLBACK_NAME = "community.general.mail"
99 CALLBACK_NEEDS_WHITELIST = True
100
101 def __init__(self, display=None):
102 super().__init__(display=display)
103 self.sender = None
104 self.to = "root"
105 self.smtphost = os.getenv("SMTPHOST", "localhost")
106 self.smtpport = 25
107 self.cc = None
108 self.bcc = None
109
110 def set_options(self, task_keys=None, var_options=None, direct=None):
111 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
112
113 self.sender = self.get_option("sender")
114 self.to = self.get_option("to")
115 self.smtphost = self.get_option("mta")
116 self.smtpport = self.get_option("mtaport")
117 self.cc = self.get_option("cc")
118 self.bcc = self.get_option("bcc")
119
120 def mail(self, subject="Ansible error mail", body=None):
121 if body is None:
122 body = subject
123
124 smtp = smtplib.SMTP(self.smtphost, port=self.smtpport)
125
126 sender_address = email.utils.parseaddr(self.sender)
127 if self.to:
128 to_addresses = email.utils.getaddresses(self.to)
129 if self.cc:
130 cc_addresses = email.utils.getaddresses(self.cc)
131 if self.bcc:
132 bcc_addresses = email.utils.getaddresses(self.bcc)
133
134 content = f"Date: {email.utils.formatdate()}\n"
135 content += f"From: {email.utils.formataddr(sender_address)}\n"
136 if self.to:
137 content += f"To: {', '.join([email.utils.formataddr(pair) for pair in to_addresses])}\n"
138 if self.cc:
139 content += f"Cc: {', '.join([email.utils.formataddr(pair) for pair in cc_addresses])}\n"
140 content += f"Message-ID: {email.utils.make_msgid(domain=self.get_option('message_id_domain'))}\n"
141 content += f"Subject: {subject.strip()}\n\n"
142 content += body
143
144 addresses = to_addresses
145 if self.cc:
146 addresses += cc_addresses
147 if self.bcc:
148 addresses += bcc_addresses
149
150 if not addresses:
151 self._display.warning("No receiver has been specified for the mail callback plugin.")
152
153 smtp.sendmail(self.sender, [address for name, address in addresses], to_bytes(content))
154
155 smtp.quit()
156
157 def subject_msg(self, multiline, failtype, linenr):
158 msg = multiline.strip("\r\n").splitlines()[linenr]
159 return f"{failtype}: {msg}"
160
161 def indent(self, multiline, indent=8):
162 return re.sub("^", " " * indent, multiline, flags=re.MULTILINE)
163
164 def body_blob(self, multiline, texttype):
165 """Turn some text output in a well-indented block for sending in a mail body"""
166 intro = f"with the following {texttype}:\n\n"
167 blob = "\n".join(multiline.strip("\r\n").splitlines())
168 return f"{intro}{self.indent(blob)}\n"
169
170 def mail_result(self, result, failtype):
171 host = result._host.get_name()
172 if not self.sender:
173 self.sender = f'"Ansible: {host}" <root>'
174
175 # Add subject
176 if self.itembody:
177 subject = self.itemsubject
178 elif result._result.get("failed_when_result") is True:
179 subject = "Failed due to 'failed_when' condition"
180 elif result._result.get("msg"):
181 subject = self.subject_msg(result._result["msg"], failtype, 0)
182 elif result._result.get("stderr"):
183 subject = self.subject_msg(result._result["stderr"], failtype, -1)
184 elif result._result.get("stdout"):
185 subject = self.subject_msg(result._result["stdout"], failtype, -1)
186 elif result._result.get("exception"): # Unrelated exceptions are added to output :-/
187 subject = self.subject_msg(result._result["exception"], failtype, -1)
188 else:
189 subject = f"{failtype}: {result._task.name or result._task.action}"
190
191 # Make playbook name visible (e.g. in Outlook/Gmail condensed view)
192 body = f"Playbook: {os.path.basename(self.playbook._file_name)}\n"
193 if result._task.name:
194 body += f"Task: {result._task.name}\n"
195 body += f"Module: {result._task.action}\n"
196 body += f"Host: {host}\n"
197 body += "\n"
198
199 # Add task information (as much as possible)
200 body += "The following task failed:\n\n"
201 if "invocation" in result._result:
202 body += self.indent(
203 f"{result._task.action}: {json.dumps(result._result['invocation']['module_args'], indent=4)}\n"
204 )
205 elif result._task.name:
206 body += self.indent(f"{result._task.name} ({result._task.action})\n")
207 else:
208 body += self.indent(f"{result._task.action}\n")
209 body += "\n"
210
211 # Add item / message
212 if self.itembody:
213 body += self.itembody
214 elif result._result.get("failed_when_result") is True:
215 fail_cond_list = "\n- ".join(result._task.failed_when)
216 fail_cond = self.indent(f"failed_when:\n- {fail_cond_list}")
217 body += f"due to the following condition:\n\n{fail_cond}\n\n"
218 elif result._result.get("msg"):
219 body += self.body_blob(result._result["msg"], "message")
220
221 # Add stdout / stderr / exception / warnings / deprecations
222 if result._result.get("stdout"):
223 body += self.body_blob(result._result["stdout"], "standard output")
224 if result._result.get("stderr"):
225 body += self.body_blob(result._result["stderr"], "error output")
226 if result._result.get("exception"): # Unrelated exceptions are added to output :-/
227 body += self.body_blob(result._result["exception"], "exception")
228 if result._result.get("warnings"):
229 for i in range(len(result._result.get("warnings"))):
230 body += self.body_blob(result._result["warnings"][i], f"exception {i + 1}")
231 if result._result.get("deprecations"):
232 for i in range(len(result._result.get("deprecations"))):
233 body += self.body_blob(result._result["deprecations"][i], f"exception {i + 1}")
234
235 body += "and a complete dump of the error:\n\n"
236 body += self.indent(f"{failtype}: {json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4)}")
237
238 self.mail(subject=subject, body=body)
239
240 def v2_playbook_on_start(self, playbook):
241 self.playbook = playbook
242 self.itembody = ""
243
244 def v2_runner_on_failed(self, result, ignore_errors=False):
245 if ignore_errors:
246 return
247
248 self.mail_result(result, "Failed")
249
250 def v2_runner_on_unreachable(self, result):
251 self.mail_result(result, "Unreachable")
252
253 def v2_runner_on_async_failed(self, result):
254 self.mail_result(result, "Async failure")
255
256 def v2_runner_item_on_failed(self, result):
257 # Pass item information to task failure
258 self.itemsubject = result._result["msg"]
259 self.itembody += self.body_blob(
260 json.dumps(result._result, cls=AnsibleJSONEncoder, indent=4), f"failed item dump '{result._result['item']}'"
261 )