Convert to byte strings to avoid UnicodeErrors

Fixes #12488
This commit is contained in:
Toshio Kuratomi 2015-09-23 15:23:29 -07:00
parent de18bcb95f
commit 5d3d9cfe0d
3 changed files with 29 additions and 18 deletions

View file

@ -19,6 +19,7 @@ import os
import time
import json
from ansible.utils.unicode import to_bytes
from ansible.plugins.callback import CallbackBase
# NOTE: in Ansible 1.2 or later general logging is available without
@ -60,9 +61,10 @@ class CallbackModule(CallbackBase):
path = os.path.join("/var/log/ansible/hosts", host)
now = time.strftime(self.TIME_FORMAT, time.localtime())
fd = open(path, "a")
fd.write(self.MSG_FORMAT % dict(now=now, category=category, data=data))
fd.close()
msg = to_bytes(self.MSG_FORMAT % dict(now=now, category=category, data=data))
with open(path, "ab") as fd:
fd.write(msg)
def runner_on_failed(self, host, res, ignore_errors=False):
self.log(host, 'FAILED', res)

View file

@ -19,6 +19,8 @@
import os
import smtplib
import json
from ansible.utils.unicode import to_bytes
from ansible.plugins.callback import CallbackBase
def mail(subject='Ansible error mail', sender=None, to=None, cc=None, bcc=None, body=None, smtphost=None):
@ -35,21 +37,27 @@ def mail(subject='Ansible error mail', sender=None, to=None, cc=None, bcc=None,
smtp = smtplib.SMTP(smtphost)
content = 'From: %s\n' % sender
content += 'To: %s\n' % to
if cc:
content += 'Cc: %s\n' % cc
content += 'Subject: %s\n\n' % subject
content += body
b_sender = to_bytes(sender)
b_to = to_bytes(to)
b_cc = to_bytes(cc)
b_subject = to_bytes(subject)
b_body = to_bytes(body)
addresses = to.split(',')
b_content = b'From: %s\n' % b_sender
b_content += b'To: %s\n' % b_to
if cc:
addresses += cc.split(',')
if bcc:
addresses += bcc.split(',')
b_content += b'Cc: %s\n' % b_cc
b_content += b'Subject: %s\n\n' % b_subject
b_content += b_body
for address in addresses:
smtp.sendmail(sender, address, content)
b_addresses = b_to.split(b',')
if b_cc:
b_addresses += b_cc.split(b',')
if b_bcc:
b_addresses += b_bcc.split(b',')
for b_address in b_addresses:
smtp.sendmail(b_sender, b_address, b_content)
smtp.quit()

View file

@ -22,6 +22,7 @@ import os
from ansible.plugins.callback import CallbackBase
from ansible.utils.path import makedirs_safe
from ansible.utils.unicode import to_bytes
from ansible.constants import TREE_DIR
@ -44,12 +45,12 @@ class CallbackModule(CallbackBase):
def write_tree_file(self, hostname, buf):
''' write something into treedir/hostname '''
buf = to_bytes(buf)
try:
makedirs_safe(self.tree)
path = os.path.join(self.tree, hostname)
fd = open(path, "w+")
fd.write(buf)
fd.close()
with open(path, 'wb+') as fd:
fd.write(buf)
except (OSError, IOError) as e:
self._display.warnings("Unable to write to %s's file: %s" % (hostname, str(e)))