]> git.apps.os.sepia.ceph.com Git - ceph-cm-ansible.git/commitdiff
failure_log: Use a default YAML representer 668/head
authorZack Cerza <zack@redhat.com>
Wed, 9 Feb 2022 00:34:25 +0000 (17:34 -0700)
committerZack Cerza <zack@redhat.com>
Wed, 9 Feb 2022 22:49:56 +0000 (15:49 -0700)
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 <zack@redhat.com>
callback_plugins/failure_log.py

index 3bcdb395afe6bf8a1f7e95f6c8fcff93a1645d3a..31632a2b1b1c5aa092ba5c9a48ab0427fa0f4d77 100644 (file)
@@ -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.