From b22c0ecc1731d758e55cb514a8bba59283640805 Mon Sep 17 00:00:00 2001 From: Zack Cerza Date: Tue, 8 Feb 2022 17:34:25 -0700 Subject: [PATCH] failure_log: Use a default YAML representer Before, we looked recursively for a certain Ansible type in the values of the dict; this broke when another type was added in Ansible, but was made worse by the type being used in _keys_, not just values. This is a better method. Signed-off-by: Zack Cerza --- callback_plugins/failure_log.py | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/callback_plugins/failure_log.py b/callback_plugins/failure_log.py index 3bcdb39..31632a2 100644 --- a/callback_plugins/failure_log.py +++ b/callback_plugins/failure_log.py @@ -14,11 +14,16 @@ import ansible ANSIBLE_MAJOR = int(ansible.__version__.split('.')[0]) if ANSIBLE_MAJOR >= 2: - from ansible.parsing.yaml.objects import AnsibleUnicode from ansible.plugins.callback import CallbackBase as callback_base else: callback_base = object +# Add a default representer so that we don't crash upon encountering +# instances of AnsibleUnicode or AnsibleUnsafeText +def default_representer(dumper, data): + return dumper.represent_scalar('tag:yaml.org,2002:str', str(data)) + +yaml.SafeDumper.add_representer(None, default_representer) log = logging.getLogger(__name__) # We only want to log if this env var is populated with @@ -38,32 +43,12 @@ def log_failure(host, result): if fail_log: failure = {"{0}".format(host): dict()} failure[host] = result - if ANSIBLE_MAJOR >= 2: - failure = sanitize_dict(failure) try: log.error(yaml.safe_dump(failure)) except Exception: log.exception("Failure object was: %s", str(failure)) -def sanitize_dict(obj): - """ - Replace AnsibleUnicode objects with strings to avoid RepresenterError when - dumping to yaml - - Only needed in ansible >= 2.0 - """ - for key in obj.keys(): - value = obj[key] - if isinstance(value, AnsibleUnicode): - value = str(value) - obj[key] = value - elif isinstance(value, dict): - value = sanitize_dict(value) - obj[key] = value - return obj - - class CallbackModule(callback_base): """ This Ansible callback plugin writes task failures to a yaml file. -- 2.39.5