Do not use str() on exceptions (#46950)

pull/46353/head
Martin Krizek 6 years ago committed by GitHub
parent 2436aa1a4e
commit a80c25cbd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -274,7 +274,7 @@ class DocCLI(CLI):
except Exception as e: except Exception as e:
display.vvv(traceback.format_exc()) display.vvv(traceback.format_exc())
raise AnsibleError( raise AnsibleError(
"%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, str(e))) "%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, to_native(e)))
def find_plugins(self, path, ptype): def find_plugins(self, path, ptype):

@ -39,7 +39,7 @@ from ansible.galaxy.api import GalaxyAPI
from ansible.galaxy.login import GalaxyLogin from ansible.galaxy.login import GalaxyLogin
from ansible.galaxy.role import GalaxyRole from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import GalaxyToken from ansible.galaxy.token import GalaxyToken
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_native, to_text
from ansible.playbook.role.requirement import RoleRequirement from ansible.playbook.role.requirement import RoleRequirement
try: try:
@ -361,7 +361,7 @@ class GalaxyCLI(CLI):
raise AnsibleError("Invalid role requirements file") raise AnsibleError("Invalid role requirements file")
f.close() f.close()
except (IOError, OSError) as e: except (IOError, OSError) as e:
raise AnsibleError('Unable to open %s: %s' % (role_file, str(e))) raise AnsibleError('Unable to open %s: %s' % (role_file, to_native(e)))
else: else:
# roles were specified directly, so we'll just go out grab them # roles were specified directly, so we'll just go out grab them
# (and their dependencies, unless the user doesn't want us to). # (and their dependencies, unless the user doesn't want us to).
@ -397,7 +397,7 @@ class GalaxyCLI(CLI):
try: try:
installed = role.install() installed = role.install()
except AnsibleError as e: except AnsibleError as e:
display.warning("- %s was NOT installed successfully: %s " % (role.name, str(e))) display.warning(u"- %s was NOT installed successfully: %s " % (role.name, to_text(e)))
self.exit_without_ignore() self.exit_without_ignore()
continue continue
@ -451,7 +451,7 @@ class GalaxyCLI(CLI):
else: else:
display.display('- %s is not installed, skipping.' % role_name) display.display('- %s is not installed, skipping.' % role_name)
except Exception as e: except Exception as e:
raise AnsibleError("Failed to remove role %s: %s" % (role_name, str(e))) raise AnsibleError("Failed to remove role %s: %s" % (role_name, to_native(e)))
return 0 return 0

@ -238,7 +238,7 @@ class GalaxyAPI(object):
done = (data.get('next_link', None) is None) done = (data.get('next_link', None) is None)
return results return results
except Exception as error: except Exception as error:
raise AnsibleError("Failed to download the %s list: %s" % (what, str(error))) raise AnsibleError("Failed to download the %s list: %s" % (what, to_native(error)))
@g_connect @g_connect
def search_roles(self, search, **kwargs): def search_roles(self, search, **kwargs):

@ -32,6 +32,7 @@ from distutils.version import LooseVersion
from shutil import rmtree from shutil import rmtree
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.urls import open_url from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI from ansible.galaxy.api import GalaxyAPI
@ -189,7 +190,7 @@ class GalaxyRole(object):
temp_file.close() temp_file.close()
return temp_file.name return temp_file.name
except Exception as e: except Exception as e:
display.error("failed to download the file: %s" % str(e)) display.error(u"failed to download the file: %s" % to_text(e))
return False return False
@ -333,7 +334,7 @@ class GalaxyRole(object):
self.path = self.paths[current + 1] self.path = self.paths[current + 1]
error = False error = False
if error: if error:
raise AnsibleError("Could not update files in %s: %s" % (self.path, str(e))) raise AnsibleError("Could not update files in %s: %s" % (self.path, to_native(e)))
# return the parsed yaml metadata # return the parsed yaml metadata
display.display("- %s was installed successfully" % str(self)) display.display("- %s was installed successfully" % str(self))
@ -341,7 +342,7 @@ class GalaxyRole(object):
try: try:
os.unlink(tmp_file) os.unlink(tmp_file)
except (OSError, IOError) as e: except (OSError, IOError) as e:
display.warning("Unable to remove tmp file (%s): %s" % (tmp_file, str(e))) display.warning(u"Unable to remove tmp file (%s): %s" % (tmp_file, to_text(e)))
return True return True
return False return False

@ -268,7 +268,7 @@ from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, get_module_path from ansible.module_utils.basic import AnsibleModule, get_module_path
from ansible.module_utils.six import b, string_types from ansible.module_utils.six import b, string_types
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native, to_text
def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir): def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir):
@ -286,7 +286,7 @@ def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir):
# if we already moved the .git dir, roll it back # if we already moved the .git dir, roll it back
if os.path.exists(repo_dir): if os.path.exists(repo_dir):
shutil.move(repo_dir, old_repo_dir) shutil.move(repo_dir, old_repo_dir)
module.fail_json(msg='Unable to move git dir. %s' % str(err)) module.fail_json(msg=u'Unable to move git dir. %s' % to_text(err))
def head_splitter(headfile, remote, module=None, fail_on_error=False): def head_splitter(headfile, remote, module=None, fail_on_error=False):
@ -690,7 +690,7 @@ def get_head_branch(git_path, module, dest, remote, bare=False):
module.fail_json( module.fail_json(
msg='Current repo does not have a valid reference to a ' msg='Current repo does not have a valid reference to a '
'separate Git dir or it refers to the invalid path', 'separate Git dir or it refers to the invalid path',
details=str(err), details=to_text(err),
) )
# Read .git/HEAD for the name of the branch. # Read .git/HEAD for the name of the branch.
# If we're in a detached HEAD state, look up the branch associated with # If we're in a detached HEAD state, look up the branch associated with
@ -992,8 +992,8 @@ def create_archive(git_path, module, dest, archive, version, repo, result):
except OSError as e: except OSError as e:
module.fail_json(msg="Failed to move %s to %s" % module.fail_json(msg="Failed to move %s to %s" %
(new_archive, archive), (new_archive, archive),
details="Error occured while moving : %s" details=u"Error occured while moving : %s"
% to_native(e)) % to_text(e))
else: else:
# Perform archive from local directory # Perform archive from local directory
git_archive(git_path, module, dest, archive, archive_fmt, version) git_archive(git_path, module, dest, archive, archive_fmt, version)
@ -1100,7 +1100,7 @@ def main():
module.fail_json( module.fail_json(
msg='Current repo does not have a valid reference to a ' msg='Current repo does not have a valid reference to a '
'separate Git dir or it refers to the invalid path', 'separate Git dir or it refers to the invalid path',
details=str(err), details=to_text(err),
) )
gitconfig = os.path.join(repo_path, 'config') gitconfig = os.path.join(repo_path, 'config')

@ -65,7 +65,7 @@ except ImportError:
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import binary_type from ansible.module_utils.six import binary_type
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes, to_text
def has_boolean_value(module, name): def has_boolean_value(module, name):
@ -238,7 +238,7 @@ def semanage_boolean_value(module, name, state):
semanage_commit(module, handle) semanage_commit(module, handle)
semanage_destroy_handle(module, handle) semanage_destroy_handle(module, handle)
except Exception as e: except Exception as e:
module.fail_json(msg="Failed to manage policy for boolean %s: %s" % (name, str(e))) module.fail_json(msg=u"Failed to manage policy for boolean %s: %s" % (name, to_text(e)))
return changed return changed

@ -282,7 +282,7 @@ class SysctlModule(object):
rc, out, err = self.module.run_command(sysctl_args) rc, out, err = self.module.run_command(sysctl_args)
if rc != 0: if rc != 0:
self.module.fail_json(msg="Failed to reload sysctl: %s" % str(out) + str(err)) self.module.fail_json(msg="Failed to reload sysctl: %s" % to_native(out) + to_native(err))
# ============================================================== # ==============================================================
# SYSCTL FILE MANAGEMENT # SYSCTL FILE MANAGEMENT
@ -297,7 +297,7 @@ class SysctlModule(object):
with open(self.sysctl_file, "r") as read_file: with open(self.sysctl_file, "r") as read_file:
lines = read_file.readlines() lines = read_file.readlines()
except IOError as e: except IOError as e:
self.module.fail_json(msg="Failed to open %s: %s" % (self.sysctl_file, to_native(e))) self.module.fail_json(msg="Failed to open %s: %s" % (to_native(self.sysctl_file), to_native(e)))
for line in lines: for line in lines:
line = line.strip() line = line.strip()

@ -19,6 +19,8 @@ import signal
import time import time
import syslog import syslog
from ansible.module_utils._text import to_text
PY3 = sys.version_info[0] == 3 PY3 = sys.version_info[0] == 3
syslog.openlog('ansible-%s' % os.path.basename(__file__)) syslog.openlog('ansible-%s' % os.path.basename(__file__))
@ -164,7 +166,7 @@ def _run_module(wrapped_cmd, jid, job_path):
result = { result = {
"failed": 1, "failed": 1,
"cmd": wrapped_cmd, "cmd": wrapped_cmd,
"msg": str(e), "msg": to_text(e),
"outdata": outdata, # temporary notice only "outdata": outdata, # temporary notice only
"stderr": stderr "stderr": stderr
} }

@ -1033,7 +1033,7 @@ class VaultEditor:
with open(filename, "rb") as fh: with open(filename, "rb") as fh:
data = fh.read() data = fh.read()
except Exception as e: except Exception as e:
raise AnsibleError(str(e)) raise AnsibleError(to_native(e))
return data return data

@ -22,6 +22,7 @@ __metaclass__ = type
import os import os
from ansible.errors import AnsibleParserError, AnsibleError from ansible.errors import AnsibleParserError, AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.six import iteritems, string_types
from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base from ansible.playbook.base import Base
@ -80,7 +81,7 @@ class RoleMetadata(Base):
role_def['name'] = def_parsed['name'] role_def['name'] = def_parsed['name']
roles.append(role_def) roles.append(role_def)
except AnsibleError as exc: except AnsibleError as exc:
raise AnsibleParserError(str(exc), obj=role_def, orig_exc=exc) raise AnsibleParserError(to_native(exc), obj=role_def, orig_exc=exc)
current_role_path = None current_role_path = None
if self._owner: if self._owner:

@ -1057,7 +1057,7 @@ class ActionBase(with_metaclass(ABCMeta, object)):
with open(source, 'rb') as src: with open(source, 'rb') as src:
src_contents = src.read() src_contents = src.read()
except Exception as e: except Exception as e:
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, str(e))) raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, to_native(e)))
if b"\x00" in src_contents: if b"\x00" in src_contents:
diff['src_binary'] = 1 diff['src_binary'] = 1

@ -41,7 +41,7 @@ class ActionModule(_ActionModule):
try: try:
self._handle_template() self._handle_template()
except ValueError as exc: except ValueError as exc:
return dict(failed=True, msg=str(exc)) return dict(failed=True, msg=to_text(exc))
result = super(ActionModule, self).run(tmp, task_vars) result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect del tmp # tmp no longer has any effect

@ -22,6 +22,7 @@ __metaclass__ = type
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from ansible.module_utils._text import to_text
from ansible.plugins.action import ActionBase from ansible.plugins.action import ActionBase
try: try:
@ -112,7 +113,7 @@ class ActionModule(ActionBase):
except TimedOutException as e: except TimedOutException as e:
result['failed'] = True result['failed'] = True
result['msg'] = str(e) result['msg'] = to_text(e)
elapsed = datetime.now() - start elapsed = datetime.now() - start
result['elapsed'] = elapsed.seconds result['elapsed'] = elapsed.seconds

@ -70,6 +70,7 @@ try:
except ImportError: except ImportError:
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils._text import to_text
from ansible.plugins.callback import CallbackBase from ansible.plugins.callback import CallbackBase
@ -152,7 +153,7 @@ class CallbackModule(CallbackBase):
verify=self.ssl_verify) verify=self.ssl_verify)
r.raise_for_status() r.raise_for_status()
except requests.exceptions.RequestException as err: except requests.exceptions.RequestException as err:
print(str(err)) print(to_text(err))
def _build_log(self, data): def _build_log(self, data):
logs = [] logs = []
@ -214,7 +215,7 @@ class CallbackModule(CallbackBase):
verify=self.ssl_verify) verify=self.ssl_verify)
r.raise_for_status() r.raise_for_status()
except requests.exceptions.RequestException as err: except requests.exceptions.RequestException as err:
print(str(err)) print(to_text(err))
self.items[host] = [] self.items[host] = []
def append_result(self, result): def append_result(self, result):

@ -24,6 +24,7 @@ import getpass
from base64 import b64encode from base64 import b64encode
from datetime import datetime from datetime import datetime
from ansible.module_utils._text import to_text
from ansible.module_utils.urls import open_url from ansible.module_utils.urls import open_url
from ansible.plugins.callback import CallbackBase from ansible.plugins.callback import CallbackBase
@ -259,4 +260,4 @@ class CallbackModule(CallbackBase):
url_username=self.grafana_user, url_password=self.grafana_password, url_username=self.grafana_user, url_password=self.grafana_password,
http_agent=self.http_agent, force_basic_auth=self.force_basic_auth) http_agent=self.http_agent, force_basic_auth=self.force_basic_auth)
except Exception as e: except Exception as e:
self._display.error('Could not submit message to Grafana: %s' % str(e)) self._display.error(u'Could not submit message to Grafana: %s' % to_text(e))

@ -111,7 +111,7 @@ try:
except ImportError: except ImportError:
HAS_FLATDICT = False HAS_FLATDICT = False
from ansible.module_utils._text import to_bytes, to_text, to_native from ansible.module_utils._text import to_bytes, to_text
from ansible.plugins.callback import CallbackBase from ansible.plugins.callback import CallbackBase
# Todo: # Todo:
@ -147,7 +147,7 @@ class PlainTextSocketAppender(object):
self.open_connection() self.open_connection()
return return
except Exception as e: except Exception as e:
self._display.vvvv("Unable to connect to Logentries: %s" % str(e)) self._display.vvvv(u"Unable to connect to Logentries: %s" % to_text(e))
root_delay *= 2 root_delay *= 2
if root_delay > self.MAX_DELAY: if root_delay > self.MAX_DELAY:
@ -247,7 +247,7 @@ class CallbackModule(CallbackBase):
self.use_tls = self.get_option('use_tls') self.use_tls = self.get_option('use_tls')
self.flatten = self.get_option('flatten') self.flatten = self.get_option('flatten')
except KeyError as e: except KeyError as e:
self._display.warning("Missing option for Logentries callback plugin: %s" % to_native(e)) self._display.warning(u"Missing option for Logentries callback plugin: %s" % to_text(e))
self.disabled = True self.disabled = True
try: try:

@ -53,6 +53,7 @@ try:
except ImportError: except ImportError:
cli = None cli = None
from ansible.module_utils._text import to_text
from ansible.module_utils.urls import open_url from ansible.module_utils.urls import open_url
from ansible.plugins.callback import CallbackBase from ansible.plugins.callback import CallbackBase
@ -124,8 +125,8 @@ class CallbackModule(CallbackBase):
response = open_url(self.webhook_url, data=data) response = open_url(self.webhook_url, data=data)
return response.read() return response.read()
except Exception as e: except Exception as e:
self._display.warning('Could not submit message to Slack: %s' % self._display.warning(u'Could not submit message to Slack: %s' %
str(e)) to_text(e))
def v2_playbook_on_start(self, playbook): def v2_playbook_on_start(self, playbook):
self.playbook_name = os.path.basename(playbook._file_name) self.playbook_name = os.path.basename(playbook._file_name)

@ -20,7 +20,7 @@ DOCUMENTATION = '''
import os import os
from ansible.constants import TREE_DIR from ansible.constants import TREE_DIR
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes, to_text
from ansible.plugins.callback import CallbackBase from ansible.plugins.callback import CallbackBase
from ansible.utils.path import makedirs_safe from ansible.utils.path import makedirs_safe
@ -53,7 +53,7 @@ class CallbackModule(CallbackBase):
with open(path, 'wb+') as fd: with open(path, 'wb+') as fd:
fd.write(buf) fd.write(buf)
except (OSError, IOError) as e: except (OSError, IOError) as e:
self._display.warning("Unable to write to %s's file: %s" % (hostname, str(e))) self._display.warning(u"Unable to write to %s's file: %s" % (hostname, to_text(e)))
def result_to_tree(self, result): def result_to_tree(self, result):
if self.tree: if self.tree:

@ -296,7 +296,7 @@ class Connection(NetworkConnectionBase):
ssh_config=ssh_config ssh_config=ssh_config
) )
except SSHUnknownHostError as exc: except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc)) raise AnsibleConnectionFailure(to_native(exc))
except ImportError as exc: except ImportError as exc:
raise AnsibleError("connection=netconf is not supported on {0}".format(self._network_os)) raise AnsibleError("connection=netconf is not supported on {0}".format(self._network_os))

@ -145,7 +145,7 @@ from ansible.module_utils.six import iteritems
from ansible.module_utils.six.moves import input from ansible.module_utils.six.moves import input
from ansible.plugins.connection import ConnectionBase from ansible.plugins.connection import ConnectionBase
from ansible.utils.path import makedirs_safe from ansible.utils.path import makedirs_safe
from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils._text import to_bytes, to_native, to_text
try: try:
from __main__ import display from __main__ import display
@ -354,10 +354,10 @@ class Connection(ConnectionBase):
except paramiko.ssh_exception.BadHostKeyException as e: except paramiko.ssh_exception.BadHostKeyException as e:
raise AnsibleConnectionFailure('host key mismatch for %s' % e.hostname) raise AnsibleConnectionFailure('host key mismatch for %s' % e.hostname)
except Exception as e: except Exception as e:
msg = str(e) msg = to_text(e)
if "PID check failed" in msg: if u"PID check failed" in msg:
raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible") raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
elif "Private key file is encrypted" in msg: elif u"Private key file is encrypted" in msg:
msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % ( msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
self._play_context.remote_user, self._play_context.remote_addr, port, msg) self._play_context.remote_user, self._play_context.remote_addr, port, msg)
raise AnsibleConnectionFailure(msg) raise AnsibleConnectionFailure(msg)
@ -380,10 +380,11 @@ class Connection(ConnectionBase):
self.ssh.get_transport().set_keepalive(5) self.ssh.get_transport().set_keepalive(5)
chan = self.ssh.get_transport().open_session() chan = self.ssh.get_transport().open_session()
except Exception as e: except Exception as e:
msg = "Failed to open session" text_e = to_text(e)
if len(str(e)) > 0: msg = u"Failed to open session"
msg += ": %s" % str(e) if text_e:
raise AnsibleConnectionFailure(msg) msg += u": %s" % text_e
raise AnsibleConnectionFailure(to_native(msg))
# sudo usually requires a PTY (cf. requiretty option), therefore # sudo usually requires a PTY (cf. requiretty option), therefore
# we give it one by default (pty=True in ansible.cfg), and we try # we give it one by default (pty=True in ansible.cfg), and we try

@ -43,7 +43,7 @@ from jinja2.filters import environmentfilter, do_groupby as _do_groupby
from ansible.errors import AnsibleError, AnsibleFilterError from ansible.errors import AnsibleError, AnsibleFilterError
from ansible.module_utils.six import iteritems, string_types, integer_types, reraise from ansible.module_utils.six import iteritems, string_types, integer_types, reraise
from ansible.module_utils.six.moves import reduce, shlex_quote from ansible.module_utils.six.moves import reduce, shlex_quote
from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common.collections import is_sequence from ansible.module_utils.common.collections import is_sequence
from ansible.module_utils.common._collections_compat import MutableMapping from ansible.module_utils.common._collections_compat import MutableMapping
from ansible.parsing.ajson import AnsibleJSONEncoder from ansible.parsing.ajson import AnsibleJSONEncoder
@ -261,7 +261,7 @@ def get_encrypted_password(password, hashtype='sha512', salt=None, salt_size=Non
try: try:
return passlib_or_crypt(password, hashtype, salt=salt, salt_size=salt_size, rounds=rounds) return passlib_or_crypt(password, hashtype, salt=salt, salt_size=salt_size, rounds=rounds)
except AnsibleError as e: except AnsibleError as e:
reraise(AnsibleFilterError, AnsibleFilterError(str(e), orig_exc=e), sys.exc_info()[2]) reraise(AnsibleFilterError, AnsibleFilterError(to_native(e), orig_exc=e), sys.exc_info()[2])
def to_uuid(string): def to_uuid(string):

@ -139,14 +139,14 @@ def logarithm(x, base=math.e):
else: else:
return math.log(x, base) return math.log(x, base)
except TypeError as e: except TypeError as e:
raise AnsibleFilterError('log() can only be used on numbers: %s' % str(e)) raise AnsibleFilterError('log() can only be used on numbers: %s' % to_native(e))
def power(x, y): def power(x, y):
try: try:
return math.pow(x, y) return math.pow(x, y)
except TypeError as e: except TypeError as e:
raise AnsibleFilterError('pow() can only be used on numbers: %s' % str(e)) raise AnsibleFilterError('pow() can only be used on numbers: %s' % to_native(e))
def inversepower(x, base=2): def inversepower(x, base=2):
@ -156,7 +156,7 @@ def inversepower(x, base=2):
else: else:
return math.pow(x, 1.0 / float(base)) return math.pow(x, 1.0 / float(base))
except (ValueError, TypeError) as e: except (ValueError, TypeError) as e:
raise AnsibleFilterError('root() can only be used on numbers: %s' % str(e)) raise AnsibleFilterError('root() can only be used on numbers: %s' % to_native(e))
def human_readable(size, isbits=False, unit=None): def human_readable(size, isbits=False, unit=None):

@ -27,7 +27,7 @@ import string
from xml.etree.ElementTree import fromstring from xml.etree.ElementTree import fromstring
from ansible.module_utils._text import to_text from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.network.common.utils import Template from ansible.module_utils.network.common.utils import Template
from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.common._collections_compat import Mapping from ansible.module_utils.common._collections_compat import Mapping
@ -96,7 +96,7 @@ def parse_cli(output, tmpl):
try: try:
template = Template() template = Template()
except ImportError as exc: except ImportError as exc:
raise AnsibleError(str(exc)) raise AnsibleError(to_native(exc))
spec = yaml.safe_load(open(tmpl).read()) spec = yaml.safe_load(open(tmpl).read())
obj = {} obj = {}
@ -241,7 +241,7 @@ def parse_cli_textfsm(value, template):
try: try:
template = open(template) template = open(template)
except IOError as exc: except IOError as exc:
raise AnsibleError(str(exc)) raise AnsibleError(to_native(exc))
re_table = textfsm.TextFSM(template) re_table = textfsm.TextFSM(template)
fsm_results = re_table.ParseText(value) fsm_results = re_table.ParseText(value)
@ -333,7 +333,7 @@ def parse_xml(output, tmpl):
try: try:
template = Template() template = Template()
except ImportError as exc: except ImportError as exc:
raise AnsibleError(str(exc)) raise AnsibleError(to_native(exc))
spec = yaml.safe_load(open(tmpl).read()) spec = yaml.safe_load(open(tmpl).read())
obj = {} obj = {}

@ -65,7 +65,7 @@ import os
from ansible.errors import AnsibleError, AnsibleParserError from ansible.errors import AnsibleError, AnsibleParserError
from ansible.plugins.lookup import LookupBase from ansible.plugins.lookup import LookupBase
from ansible.module_utils.urls import open_url from ansible.module_utils.urls import open_url
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.six.moves.urllib.error import HTTPError from ansible.module_utils.six.moves.urllib.error import HTTPError
try: try:
@ -118,7 +118,7 @@ class GrafanaAPI:
try: try:
r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST') r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST')
except HTTPError as e: except HTTPError as e:
raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(e))) raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, to_native(e)))
if r.getcode() != 200: if r.getcode() != 200:
raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode()))) raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode())))
@ -144,12 +144,12 @@ class GrafanaAPI:
else: else:
r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET') r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET')
except HTTPError as e: except HTTPError as e:
raise GrafanaAPIException('Unable to search dashboards : %s' % str(e)) raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e))
if r.getcode() == 200: if r.getcode() == 200:
try: try:
dashboard_list = json.loads(r.read()) dashboard_list = json.loads(r.read())
except Exception as e: except Exception as e:
raise GrafanaAPIException('Unable to parse json list %s' % str(e)) raise GrafanaAPIException('Unable to parse json list %s' % to_native(e))
else: else:
raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode())) raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode()))

@ -23,7 +23,7 @@ import json
import re import re
from ansible import constants as C from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected from ansible.plugins.netconf import ensure_connected
@ -116,7 +116,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout timeout=obj._play_context.timeout
) )
except SSHUnknownHostError as exc: except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc)) raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None guessed_os = None
for c in m.server_capabilities: for c in m.server_capabilities:

@ -25,6 +25,7 @@ import re
import collections import collections
from ansible import constants as C from ansible import constants as C
from ansible.module_utils._text import to_native
from ansible.module_utils.network.common.netconf import remove_namespaces from ansible.module_utils.network.common.netconf import remove_namespaces
from ansible.module_utils.network.iosxr.iosxr import build_xml, etree_find from ansible.module_utils.network.iosxr.iosxr import build_xml, etree_find
from ansible.errors import AnsibleConnectionFailure, AnsibleError from ansible.errors import AnsibleConnectionFailure, AnsibleError
@ -111,7 +112,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout timeout=obj._play_context.timeout
) )
except SSHUnknownHostError as exc: except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc)) raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None guessed_os = None
for c in m.server_capabilities: for c in m.server_capabilities:

@ -23,7 +23,7 @@ import json
import re import re
from ansible import constants as C from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected from ansible.plugins.netconf import ensure_connected
@ -120,7 +120,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout timeout=obj._play_context.timeout
) )
except SSHUnknownHostError as exc: except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc)) raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None guessed_os = None
for c in m.server_capabilities: for c in m.server_capabilities:

@ -23,7 +23,7 @@ import json
import re import re
from ansible import constants as C from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected from ansible.plugins.netconf import ensure_connected
@ -89,7 +89,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout timeout=obj._play_context.timeout
) )
except SSHUnknownHostError as exc: except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc)) raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None guessed_os = None
for c in m.server_capabilities: for c in m.server_capabilities:

@ -969,7 +969,7 @@ class StrategyBase:
for host in included_file._hosts: for host in included_file._hosts:
iterator.mark_host_failed(host) iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True self._tqm._failed_hosts[host.name] = True
display.warning(str(e)) display.warning(to_text(e))
continue continue
# remove hosts from notification list # remove hosts from notification list

@ -235,7 +235,7 @@ class StrategyModule(StrategyBase):
except AnsibleError as e: except AnsibleError as e:
for host in included_file._hosts: for host in included_file._hosts:
iterator.mark_host_failed(host) iterator.mark_host_failed(host)
display.warning(str(e)) display.warning(to_text(e))
continue continue
for new_block in new_blocks: for new_block in new_blocks:

Loading…
Cancel
Save