gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __call__(self):
    choice_map = {
        "present": self.init_swarm,
        "join": self.join,
        "absent": self.leave,
        "remove": self.remove,
        "inspect": self.inspect_swarm,
    }

    choice_map.get(self.parameters.state)()


# Traceback (nKeyError)
fatal: [node-01]: FAILED! => {"changed": false, "module_stderr": "Shared connection to node-01 closed.\r\n", "module_stdout": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.24.1) or chardet (2.2.1) doesn't match a supported version!\r\n  RequestsDependencyWarning)\r\nTraceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 113, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 105, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 48, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 535, in <module>\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 530, in main\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 310, in __call__\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 333, in init_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 390, in __update_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 376, in __update_spec\r\nKeyError: 'Labels'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __call__(self):
    choice_map = {
        "present": self.init_swarm,
        "join": self.join,
        "absent": self.leave,
        "remove": self.remove,
        "inspect": self.inspect_swarm,
    }

    choice_map.get(self.state)()
# Buggy code
def join(self):
    if self.__isSwarmNode():
        self.results["actions"].append("This node is already part of a swarm.")
        return
    if not self.check_mode:
        try:
            self.client.join_swarm(
                remote_addrs=self.parameters.remote_addrs,
                join_token=self.parameters.join_token,
                listen_addr=self.parameters.listen_addr,
                advertise_addr=self.parameters.advertise_addr,
            )
        except APIError as exc:
            self.client.fail("Can not join the Swarm Cluster: %s" % to_native(exc))
    self.results["actions"].append("New node is added to swarm cluster")
    self.results["changed"] = True


# Traceback (nKeyError)
fatal: [node-01]: FAILED! => {"changed": false, "module_stderr": "Shared connection to node-01 closed.\r\n", "module_stdout": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.24.1) or chardet (2.2.1) doesn't match a supported version!\r\n  RequestsDependencyWarning)\r\nTraceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 113, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 105, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 48, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 535, in <module>\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 530, in main\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 310, in __call__\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 333, in init_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 390, in __update_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 376, in __update_spec\r\nKeyError: 'Labels'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def join(self):
    if self.__isSwarmNode():
        self.results["actions"].append("This node is already part of a swarm.")
        return
    if not self.check_mode:
        try:
            self.client.join_swarm(
                remote_addrs=self.parameters.remote_addrs,
                join_token=self.parameters.join_token,
                listen_addr=self.parameters.listen_addr,
                advertise_addr=self.parameters.advertise_addr,
            )
        except APIError as exc:
            self.client.fail("Can not join the Swarm Cluster: %s" % to_native(exc))
    self.results["actions"].append("New node is added to swarm cluster")
    self.differences.add("joined", parameter=True, active=False)
    self.results["changed"] = True
# Buggy code
def leave(self):
    if not (self.__isSwarmNode()):
        self.results["actions"].append("This node is not part of a swarm.")
        return
    if not self.check_mode:
        try:
            self.client.leave_swarm(force=self.parameters.force)
        except APIError as exc:
            self.client.fail(
                "This node can not leave the Swarm Cluster: %s" % to_native(exc)
            )
    self.results["actions"].append("Node has left the swarm cluster")
    self.results["changed"] = True


# Traceback (nKeyError)
fatal: [node-01]: FAILED! => {"changed": false, "module_stderr": "Shared connection to node-01 closed.\r\n", "module_stdout": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.24.1) or chardet (2.2.1) doesn't match a supported version!\r\n  RequestsDependencyWarning)\r\nTraceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 113, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 105, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 48, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 535, in <module>\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 530, in main\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 310, in __call__\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 333, in init_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 390, in __update_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 376, in __update_spec\r\nKeyError: 'Labels'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def leave(self):
    if not (self.__isSwarmNode()):
        self.results["actions"].append("This node is not part of a swarm.")
        return
    if not self.check_mode:
        try:
            self.client.leave_swarm(force=self.force)
        except APIError as exc:
            self.client.fail(
                "This node can not leave the Swarm Cluster: %s" % to_native(exc)
            )
    self.results["actions"].append("Node has left the swarm cluster")
    self.differences.add("joined", parameter="absent", active="present")
    self.results["changed"] = True
# Buggy code
def create_file(path, content):
    with open(path, "wb") as f:
        f.write(content)
    return path


# Traceback (TypeError)
(No output)
OS / ENVIRONMENT
Target OS: Ubuntu 16.04.5 LTS
STEPS TO REPRODUCE
- name: 'Write Wildfly keystore'
java_keystore:
name: tau-wildfly
certificate: "{{ tau_certificate_chain[0] }}"
private_key: "{{ tau_private_key }}"
password: changeit
dest: '{{ tau_wildfly_keystore }}'
owner: '{{ tau_user }}'
group: '{{ tau_group }}'
mode: 'u=rw,go='
EXPECTED RESULTS
Task runs and creates/updates keystore
ACTUAL RESULTS


TASK [tau_common/server-keys : Write Wildfly keystore] *************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: a bytes-like object is required, not 'str'
fatal: [REDACTED]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"<stdin>\", line 113, in <module>\n  File \"<stdin>\", line 105, in _ansiballz_main\n  File \"<stdin>\", line 48, in invoke_module\n  File \"/usr/lib/python3.5/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n  File \"/usr/lib/python3.5/imp.py\", line 170, in load_source\n    module = _exec(spec, sys.modules[name])\n  File \"<frozen importlib._bootstrap>\", line 626, in _exec\n  File \"<frozen importlib._bootstrap_external>\", line 665, in exec_module\n  File \"<frozen importlib._bootstrap>\", line 222, in _call_with_frames_removed\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 290, in <module>\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 286, in main\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 261, in process_jks\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 193, in create_jks\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 172, in create_tmp_certificate\n  File \"/tmp/ansible_java_keystore_payload_ky7c0l_e/__main__.py\", line 167, in create_file\nTypeError: a bytes-like object is required, not 'str'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def create_file(path, content):
    with open(path, "w") as f:
        f.write(content)
    return path
# Buggy code
def convert_to_bytes(param):
    """
    This method convert units to bytes, which follow IEC standard.

    :param param: value to be converted
    """
    if param is None:
        return None

    # Get rid of whitespaces:
    param = "".join(param.split())

    # Convert to bytes:
    if param[-3].lower() in ["k", "m", "g", "t", "p"]:
        return int(param[:-3]) * BYTES_MAP.get(param[-3:].lower(), 1)
    elif param.isdigit():
        return int(param) * 2**10
    else:
        raise ValueError(
            "Unsupported value(IEC supported): '{value}'".format(value=param)
        )


# Traceback (IndexError)
ballZ_ovirt_vm.py &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1539046469.46-29856170959741/AnsiballZ_ovirt_vm.py &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1539046469.46-29856170959741/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_ovirt_vm_payload_T0dufZ/__main__.py", line 2012, in main
clone_permissions=module.params['clone_permissions'],
File "/tmp/ansible_ovirt_vm_payload_T0dufZ/ansible_ovirt_vm_payload.zip/ansible/module_utils/ovirt.py", line 558, in create
new_entity = self.build_entity()
File "/tmp/ansible_ovirt_vm_payload_T0dufZ/__main__.py", line 1087, in build_entity
) if self.param('memory') else None,
File "/tmp/ansible_ovirt_vm_payload_T0dufZ/ansible_ovirt_vm_payload.zip/ansible/module_utils/ovirt.py", line 168, in convert_to_bytes
if param[-3].lower() in ['k', 'm', 'g', 't', 'p']:
IndexError: string index out of range

# Fixed code
def convert_to_bytes(param):
    """
    This method convert units to bytes, which follow IEC standard.

    :param param: value to be converted
    """
    if param is None:
        return None

    # Get rid of whitespaces:
    param = "".join(param.split())

    # Convert to bytes:
    if len(param) > 3 and param[-3].lower() in ["k", "m", "g", "t", "p"]:
        return int(param[:-3]) * BYTES_MAP.get(param[-3:].lower(), 1)
    elif param.isdigit():
        return int(param) * 2**10
    else:
        raise ValueError(
            "Unsupported value(IEC supported): '{value}'".format(value=param)
        )
# Buggy code
def set_value(module):
    consul_api = get_consul_api(module)

    key = module.params.get("key")
    value = module.params.get("value")

    if value is NOT_SET:
        raise AssertionError('Cannot set value of "%s" to `NOT_SET`', (key,))

    index, changed = _has_value_changed(consul_api, key, value)

    if changed and not module.check_mode:
        changed = consul_api.kv.put(
            key, value, cas=module.params.get("cas"), flags=module.params.get("flags")
        )

    stored = None
    if module.params.get("retrieve"):
        index, stored = consul_api.kv.get(key)

    module.exit_json(changed=changed, index=index, key=key, data=stored)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 113, in <module>
_ansiballz_main()
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 105, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 48, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/usr/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/usr/lib/python3.7/imp.py", line 169, in load_source
module = _exec(spec, sys.modules[name])
File "<frozen importlib._bootstrap>", line 630, in _exec
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 550, in <module>
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 518, in main
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 436, in add_source
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 349, in _add_valid_source
RuntimeError: generator raised StopIteration

# Fixed code
def set_value(module):
    consul_api = get_consul_api(module)

    key = module.params.get("key")
    value = module.params.get("value")

    if value is NOT_SET:
        raise AssertionError('Cannot set value of "%s" to `NOT_SET`' % key)

    index, changed = _has_value_changed(consul_api, key, value)

    if changed and not module.check_mode:
        changed = consul_api.kv.put(
            key, value, cas=module.params.get("cas"), flags=module.params.get("flags")
        )

    stored = None
    if module.params.get("retrieve"):
        index, stored = consul_api.kv.get(key)

    module.exit_json(changed=changed, index=index, key=key, data=stored)
# Buggy code
def __iter__(self):
    """Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped."""
    for file, sources in self.files.items():
        for n, valid, enabled, source, comment in sources:
            if valid:
                yield file, n, enabled, source, comment
    raise StopIteration


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 113, in <module>
_ansiballz_main()
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 105, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 48, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/usr/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/usr/lib/python3.7/imp.py", line 169, in load_source
module = _exec(spec, sys.modules[name])
File "<frozen importlib._bootstrap>", line 630, in _exec
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 550, in <module>
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 518, in main
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 436, in add_source
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 349, in _add_valid_source
RuntimeError: generator raised StopIteration

# Fixed code
def __iter__(self):
    """Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped."""
    for file, sources in self.files.items():
        for n, valid, enabled, source, comment in sources:
            if valid:
                yield file, n, enabled, source, comment
# Buggy code
def _grouper(self, tgtkey):
    while self.currkey == tgtkey:
        yield self.currvalue
        self.currvalue = next(self.it)  # Exit on StopIteration
        self.currkey = self.keyfunc(self.currvalue)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 113, in <module>
_ansiballz_main()
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 105, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/vagrant/.ansible/tmp/ansible-tmp-1548149534.5508606-278949110624512/AnsiballZ_apt_repository.py", line 48, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/usr/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/usr/lib/python3.7/imp.py", line 169, in load_source
module = _exec(spec, sys.modules[name])
File "<frozen importlib._bootstrap>", line 630, in _exec
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 550, in <module>
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 518, in main
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 436, in add_source
File "/tmp/ansible_apt_repository_payload_fib2nr65/__main__.py", line 349, in _add_valid_source
RuntimeError: generator raised StopIteration

# Fixed code
def _grouper(self, tgtkey):
    while self.currkey == tgtkey:
        yield self.currvalue
        try:
            self.currvalue = next(self.it)  # Exit on StopIteration
        except StopIteration:
            return
        self.currkey = self.keyfunc(self.currvalue)
# Buggy code
def __init__(self, play_context, new_stdin, *args, **kwargs):
    super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)

    self._ssh_shell = None

    self._matched_prompt = None
    self._matched_cmd_prompt = None
    self._matched_pattern = None
    self._last_response = None
    self._history = list()

    self._terminal = None
    self.cliconf = None
    self.paramiko_conn = None

    if self._play_context.verbosity > 3:
        logging.getLogger("paramiko").setLevel(logging.DEBUG)


# Traceback (KeyError)
TASK [ios_facts] ***********************************************************************************************************************************************************************************************************************
task path: /home/pffs/change-scripts/ansible/script.yaml:9
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_3_5Dr3/ansible_module_ios_facts.py", line 525, in <module>
main()
File "/tmp/ansible_3_5Dr3/ansible_module_ios_facts.py", line 511, in main
inst.populate()
File "/tmp/ansible_3_5Dr3/ansible_module_ios_facts.py", line 281, in populate
self.populate_ipv4_interfaces(data)
File "/tmp/ansible_3_5Dr3/ansible_module_ios_facts.py", line 316, in populate_ipv4_interfaces
self.facts['interfaces'][key]['ipv4'] = list()
KeyError: u'Serial0/3/0'

fatal: [1.2.3.4]: FAILED! => {
"changed": false,
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def __init__(self, play_context, new_stdin, *args, **kwargs):
    super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)

    self._ssh_shell = None

    self._matched_prompt = None
    self._matched_cmd_prompt = None
    self._matched_pattern = None
    self._last_response = None
    self._history = list()
    self._command_response = None

    self._terminal = None
    self.cliconf = None
    self.paramiko_conn = None

    if self._play_context.verbosity > 3:
        logging.getLogger("paramiko").setLevel(logging.DEBUG)
# Buggy code
def _exec_jsonrpc(self, name, *args, **kwargs):
    req = request_builder(name, *args, **kwargs)
    reqid = req["id"]

    if not os.path.exists(self.socket_path):
        raise ConnectionError(
            "socket_path does not exist or cannot be found."
            "\nSee the socket_path issue catergory in Network Debug and Troubleshooting Guide"
        )

    try:
        data = json.dumps(req)
        out = self.send(data)
        response = json.loads(out)

    except socket.error as e:
        raise ConnectionError(
            "unable to connect to socket. See the socket_path issue catergory in Network Debug and Troubleshooting Guide",
            err=to_text(e, errors="surrogate_then_replace"),
            exception=traceback.format_exc(),
        )

    if response["id"] != reqid:
        raise ConnectionError("invalid json-rpc id received")

    return response


# Traceback (TypeError)
fatal: [redacted]: FAILED! => {"msg": "Traceback (most recent call last):
File \"/usr/bin/ansible-connection\", line 321, in <module>
main()
File \"/usr/bin/ansible-connection\", line 287, in main
conn.set_options(var_options=variables)
File \"/usr/lib/python2.7/site-packages/ansible/module_utils/connection.py\", line 167, in __rpc__
response = self._exec_jsonrpc(name, *args, **kwargs)
File \"/usr/lib/python2.7/site-packages/ansible/module_utils/connection.py\", line 144, in _exec_jsonrpc
data = json.dumps(req)
File \"/usr/lib/python2.7/json/__init__.py\", line 244, in dumps
return _default_encoder.encode(obj)
File \"/usr/lib/python2.7/json/encoder.py\", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File \"/usr/lib/python2.7/json/encoder.py\", line 270, in iterencode
return _iterencode(o, 0)
File \"/usr/lib/python2.7/json/encoder.py\", line 184, in default
raise TypeError(repr(o) + \" is not JSON serializable\")
TypeError: u'***redacted***' is not JSON serializable
"}

# Fixed code
def _exec_jsonrpc(self, name, *args, **kwargs):
    req = request_builder(name, *args, **kwargs)
    reqid = req["id"]

    if not os.path.exists(self.socket_path):
        raise ConnectionError(
            "socket_path does not exist or cannot be found."
            "\nSee the socket_path issue catergory in Network Debug and Troubleshooting Guide"
        )

    try:
        data = json.dumps(req, cls=AnsibleJSONEncoder)
    except TypeError as exc:
        raise ConnectionError(
            "Failed to encode some variables as JSON for communication with ansible-connection. "
            "The original exception was: %s" % to_text(exc)
        )

    try:
        out = self.send(data)
        response = json.loads(out)

    except socket.error as e:
        raise ConnectionError(
            "unable to connect to socket. See the socket_path issue catergory in Network Debug and Troubleshooting Guide",
            err=to_text(e, errors="surrogate_then_replace"),
            exception=traceback.format_exc(),
        )

    if response["id"] != reqid:
        raise ConnectionError("invalid json-rpc id received")

    return response
# Buggy code
def decorator(func):
    def _handle_timeout(signum, frame):
        msg = "Timer expired after %s seconds" % globals().get("GATHER_TIMEOUT")
        raise TimeoutError(msg)

    def wrapper(*args, **kwargs):
        local_seconds = seconds
        if local_seconds is None:
            local_seconds = globals().get("GATHER_TIMEOUT") or DEFAULT_GATHER_TIMEOUT
        signal.signal(signal.SIGALRM, _handle_timeout)
        signal.alarm(local_seconds)

        try:
            result = func(*args, **kwargs)
        finally:
            signal.alarm(0)
        return result

    return wrapper


# Traceback (TimeoutError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_d9POp0/ansible_modlib.zip/ansible/module_utils/basic.py", line 2853, in run_command
cmd = subprocess.Popen(args, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1308, in _execute_child
data = _eintr_retry_call(os.read, errpipe_read, 1048576)
File "/usr/lib64/python2.7/subprocess.py", line 478, in _eintr_retry_call
return func(*args)
File "/tmp/ansible_d9POp0/ansible_modlib.zip/ansible/module_utils/facts/timeout.py", line 37, in _handle_timeout
raise TimeoutError(msg)
TimeoutError: Timer expired after 10 seconds

fatal: [kso-nlape1vp-rano-009]: FAILED! => {
"changed": false,
"cmd": "/usr/bin/udevadm info --query property --name /dev/sda1",
"invocation": {
"module_args": {
"fact_path": "/etc/ansible/facts.d",
"filter": "*",
"gather_subset": [
"all"
],
"gather_timeout": 10
}
},
"msg": "Timer expired after 10 seconds",
"rc": 257
}

# Fixed code
def decorator(func):
    def wrapper(*args, **kwargs):
        timeout_value = seconds
        if timeout_value is None:
            timeout_value = globals().get("GATHER_TIMEOUT") or DEFAULT_GATHER_TIMEOUT

        pool = mp.ThreadPool(processes=1)
        res = pool.apply_async(func, args, kwargs)
        pool.close()
        try:
            return res.get(timeout_value)
        except multiprocessing.TimeoutError:
            # This is an ansible.module_utils.common.facts.timeout.TimeoutError
            raise TimeoutError("Timer expired after %s seconds" % timeout_value)

    return wrapper
# Buggy code
def wrapper(*args, **kwargs):
    local_seconds = seconds
    if local_seconds is None:
        local_seconds = globals().get("GATHER_TIMEOUT") or DEFAULT_GATHER_TIMEOUT
    signal.signal(signal.SIGALRM, _handle_timeout)
    signal.alarm(local_seconds)

    try:
        result = func(*args, **kwargs)
    finally:
        signal.alarm(0)
    return result


# Traceback (TimeoutError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_d9POp0/ansible_modlib.zip/ansible/module_utils/basic.py", line 2853, in run_command
cmd = subprocess.Popen(args, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1308, in _execute_child
data = _eintr_retry_call(os.read, errpipe_read, 1048576)
File "/usr/lib64/python2.7/subprocess.py", line 478, in _eintr_retry_call
return func(*args)
File "/tmp/ansible_d9POp0/ansible_modlib.zip/ansible/module_utils/facts/timeout.py", line 37, in _handle_timeout
raise TimeoutError(msg)
TimeoutError: Timer expired after 10 seconds

fatal: [kso-nlape1vp-rano-009]: FAILED! => {
"changed": false,
"cmd": "/usr/bin/udevadm info --query property --name /dev/sda1",
"invocation": {
"module_args": {
"fact_path": "/etc/ansible/facts.d",
"filter": "*",
"gather_subset": [
"all"
],
"gather_timeout": 10
}
},
"msg": "Timer expired after 10 seconds",
"rc": 257
}

# Fixed code
def wrapper(*args, **kwargs):
    timeout_value = seconds
    if timeout_value is None:
        timeout_value = globals().get("GATHER_TIMEOUT") or DEFAULT_GATHER_TIMEOUT

    pool = mp.ThreadPool(processes=1)
    res = pool.apply_async(func, args, kwargs)
    pool.close()
    try:
        return res.get(timeout_value)
    except multiprocessing.TimeoutError:
        # This is an ansible.module_utils.common.facts.timeout.TimeoutError
        raise TimeoutError("Timer expired after %s seconds" % timeout_value)
# Buggy code
def load_current_config(self):
    # called in base class in run function
    self._current_config = dict()
    magp_data = self._get_magp_config()
    if magp_data:
        self._update_magp_data(magp_data)


# Traceback (nAttributeError)
fatal: [sn2410_leaf1_1]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 227, in <module>\n    main()\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 223, in main\n    OnyxMagpModule.main()\n  File \"/tmp/ansible_2cIQBk/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 240, in main\n  File \"/tmp/ansible_2cIQBk/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 218, in run\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 150, in load_current_config\n    self._update_magp_data(magp_data)\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 137, in _update_magp_data\n    magp_id = self.get_magp_id(magp_item)\n  File \"/tmp/ansible_2cIQBk/ansible_module_onyx_magp.py\", line 123, in get_magp_id\n    return int(header.split()[1])\nAttributeError: 'NoneType' object has no attribute 'split'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def load_current_config(self):
    # called in base class in run function
    self._os_version = self._get_os_version()
    self._current_config = dict()
    magp_data = self._get_magp_config()
    if magp_data:
        self._update_magp_data(magp_data)
# Buggy code
def set(self, key, value):
    value2 = json.dumps(value)
    if self._timeout > 0:  # a timeout of 0 is handled as meaning 'never expire'
        self._db.setex(self._make_key(key), int(self._timeout), value2)
    else:
        self._db.set(self._make_key(key), value2)

    self._db.zadd(self._keys_set, time.time(), key)
    self._cache[key] = value


# Traceback (TypeError)
PLAY [all] *****************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************
task path: /home/user/some.git/setup_basic_servers.yml:4
ERROR! Unexpected Exception, this is probably a bug: 'float' object has no attribute 'items'
to see the full traceback, use -vvv
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/user/.virtualenvs/ansible-py3/lib/python3.6/site-packages/ansible/plugins/strategy/__init__.py", line 90, in results_thread_main
result = strategy._final_q.get()
File "/usr/lib/python3.6/multiprocessing/queues.py", line 94, in get
res = self._recv_bytes()
File "/usr/lib/python3.6/multiprocessing/connection.py", line 216, in recv_bytes
buf = self._recv_bytes(maxlength)
File "/usr/lib/python3.6/multiprocessing/connection.py", line 411, in _recv_bytes
return self._recv(size)
File "/usr/lib/python3.6/multiprocessing/connection.py", line 379, in _recv
chunk = read(handle, remaining)
TypeError: an integer is required (got type NoneType)

# Fixed code
def set(self, key, value):
    value2 = json.dumps(value)
    if self._timeout > 0:  # a timeout of 0 is handled as meaning 'never expire'
        self._db.setex(self._make_key(key), int(self._timeout), value2)
    else:
        self._db.set(self._make_key(key), value2)

    if VERSION[0] == 2:
        self._db.zadd(self._keys_set, time.time(), key)
    else:
        self._db.zadd(self._keys_set, {key: time.time()})
    self._cache[key] = value
# Buggy code
def get_allowed_vlans(cls, if_data):
    allowed_vlans = cls.get_config_attr(if_data, "Allowed vlans")
    if allowed_vlans:
        vlans = allowed_vlans.split(",")
        allowed_vlans = [int(vlan.strip()) for vlan in vlans]
    return allowed_vlans


# Traceback (ValueError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: invalid literal for int() with base 10: 'N/A'
fatal: [l-csi-2700-03]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 288, in <module>\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 284, in main\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/ansible_onyx_l2_interface_payload.zip/ansible/module_utils/network/onyx/onyx.py\", line 249, in main\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/ansible_onyx_l2_interface_payload.zip/ansible/module_utils/network/onyx/onyx.py\", line 227, in run\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 187, in load_current_config\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 171, in _create_switchport_data\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 162, in get_access_vlan\nValueError: invalid literal for int() with base 10: 'N/A'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
to retry, use: --limit @/swgwork/eddies/ansible/lab/case_488640/l2_interface.retry

# Fixed code
def get_allowed_vlans(cls, if_data):
    allowed_vlans = cls.get_config_attr(if_data, "Allowed vlans")
    interface_allwoed_vlans = []
    if allowed_vlans:
        vlans = [x.strip() for x in allowed_vlans.split(",")]
        for vlan in vlans:
            if "-" not in vlan:
                interface_allwoed_vlans.append(int(vlan))
            else:
                vlan_range = vlan.split("-")
                min_number = int(vlan_range[0].strip())
                max_number = int(vlan_range[1].strip())
                vlan_list = range(min_number, max_number + 1)
                interface_allwoed_vlans.extend(vlan_list)
    return interface_allwoed_vlans
# Buggy code
def get_access_vlan(cls, if_data):
    access_vlan = cls.get_config_attr(if_data, "Access vlan")
    if access_vlan:
        return int(access_vlan)


# Traceback (ValueError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: invalid literal for int() with base 10: 'N/A'
fatal: [l-csi-2700-03]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/root/.ansible/tmp/ansible-local-162000Bkv_Bv/ansible-tmp-1538555779.75-97896039323320/AnsiballZ_onyx_l2_interface.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 288, in <module>\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 284, in main\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/ansible_onyx_l2_interface_payload.zip/ansible/module_utils/network/onyx/onyx.py\", line 249, in main\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/ansible_onyx_l2_interface_payload.zip/ansible/module_utils/network/onyx/onyx.py\", line 227, in run\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 187, in load_current_config\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 171, in _create_switchport_data\n  File \"/tmp/ansible_onyx_l2_interface_payload_Y_eddw/__main__.py\", line 162, in get_access_vlan\nValueError: invalid literal for int() with base 10: 'N/A'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
to retry, use: --limit @/swgwork/eddies/ansible/lab/case_488640/l2_interface.retry

# Fixed code
def get_access_vlan(cls, if_data):
    access_vlan = cls.get_config_attr(if_data, "Access vlan")
    if access_vlan:
        try:
            return int(access_vlan)
        except ValueError:
            return None
# Buggy code
def has_permissions_modifications(self):
    return sorted(self._permissions) != sorted(self.permissions)


# Traceback (TypeError)
Traceback (most recent call last):
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 261, in <module>
_ansiballz_main()
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 251, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 119, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File \"/usr/lib/python3.6/imp.py\", line 235, in load_module
return load_source(name, filename, file)
File \"/usr/lib/python3.6/imp.py\", line 170, in load_source
module = _exec(spec, sys.modules[name])
File \"<frozen importlib._bootstrap>\", line 618, in _exec
File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module
File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 317, in <module>
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 304, in main
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 233, in has_permissions_modifications
TypeError: '<' not supported between instances of 'dict' and 'dict'

# Fixed code
def has_permissions_modifications(self):
    sort_key_fetch = operator.itemgetter("vhost")
    return sorted(self._permissions, key=sort_key_fetch) != sorted(
        self.permissions, key=sort_key_fetch
    )
# Buggy code
def set_permissions(self):
    for permission in self._permissions:
        if permission not in self.permissions:
            cmd = ["clear_permissions", "-p"]
            cmd.append(permission["vhost"])
            cmd.append(self.username)
            self._exec(cmd)
    for permission in self.permissions:
        if permission not in self._permissions:
            cmd = ["set_permissions", "-p"]
            cmd.append(permission["vhost"])
            cmd.append(self.username)
            cmd.append(permission["configure_priv"])
            cmd.append(permission["write_priv"])
            cmd.append(permission["read_priv"])
            self._exec(cmd)


# Traceback (TypeError)
Traceback (most recent call last):
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 261, in <module>
_ansiballz_main()
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 251, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 119, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File \"/usr/lib/python3.6/imp.py\", line 235, in load_module
return load_source(name, filename, file)
File \"/usr/lib/python3.6/imp.py\", line 170, in load_source
module = _exec(spec, sys.modules[name])
File \"<frozen importlib._bootstrap>\", line 618, in _exec
File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module
File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 317, in <module>
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 304, in main
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 233, in has_permissions_modifications
TypeError: '<' not supported between instances of 'dict' and 'dict'

# Fixed code
def set_permissions(self):
    permissions_to_clear = [
        permission
        for permission in self._permissions
        if permission not in self.permissions
    ]
    permissions_to_add = [
        permission
        for permission in self.permissions
        if permission not in self._permissions
    ]
    for permission in permissions_to_clear:
        cmd = "clear_permissions -p {vhost} {username}".format(
            username=self.username, vhost=permission["vhost"]
        )
        self._exec(cmd.split(" "))
    for permission in permissions_to_add:
        cmd = "set_permissions -p {vhost} {username} {configure_priv} {write_priv} {read_priv}".format(
            username=self.username, **permission
        )
        self._exec(cmd.split(" "))
# Buggy code
def has_permissions_modifications(self):
    sort_key_fetch = operator.itemgetter("vhost")
    return sorted(self._permissions, key=sort_key_fetch) != sorted(
        self.permissions, key=sort_key_fetch
    )


# Traceback (TypeError)
Traceback (most recent call last):
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 261, in <module>
_ansiballz_main()
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 251, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File \"/home/user/.ansible/tmp/ansible-tmp-1543222268.31-229234673963142/AnsiballZ_rabbitmq_user.py\", line 119, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File \"/usr/lib/python3.6/imp.py\", line 235, in load_module
return load_source(name, filename, file)
File \"/usr/lib/python3.6/imp.py\", line 170, in load_source
module = _exec(spec, sys.modules[name])
File \"<frozen importlib._bootstrap>\", line 618, in _exec
File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module
File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 317, in <module>
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 304, in main
File \"/tmp/ansible_rabbitmq_user_payload_yjcxsat6/__main__.py\", line 233, in has_permissions_modifications
TypeError: '<' not supported between instances of 'dict' and 'dict'

# Fixed code
def has_permissions_modifications(self):
    def to_permission_tuple(vhost_permission_dict):
        return vhost_permission_dict["vhost"], vhost_permission_dict

    def permission_dict(vhost_permission_list):
        return dict(map(to_permission_tuple, vhost_permission_list))

    return permission_dict(self._permissions) != permission_dict(self.permissions)
# Buggy code
def _system_state_change(state, records, description, ttl, zone, recordset):
    if state == "present":
        if recordset is None:
            return True
        if records is not None and recordset.records != records:
            return True
        if description is not None and recordset.description != description:
            return True
        if ttl is not None and recordset.ttl != ttl:
            return True
    if state == "absent" and recordset:
        return True
    return False


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/9b/d7gxcd593hj6k54zk8gh19b55dmxzn/T/ansible_vr2cn8s0/ansible_module_os_recordset.py", line 236, in <module>
main()
File "/var/folders/9b/d7gxcd593hj6k54zk8gh19b55dmxzn/T/ansible_vr2cn8s0/ansible_module_os_recordset.py", line 172, in main
recordsets = cloud.search_recordsets(zone, name_or_id=name + '.' + zone, filters=recordset_filter)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openstack/cloud/openstackcloud.py", line 8551, in search_recordsets
return _utils._filter_list(recordsets, name_or_id, filters)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openstack/cloud/_utils.py", line 113, in _filter_list
e_id = _make_unicode(e.get('id', None))
AttributeError: 'str' object has no attribute 'get'

fatal: [localhost]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/9b/d7gxcd593hj6k54zk8gh19b55dmxzn/T/ansible_vr2cn8s0/ansible_module_os_recordset.py\", line 236, in <module>\n    main()\n  File \"/var/folders/9b/d7gxcd593hj6k54zk8gh19b55dmxzn/T/ansible_vr2cn8s0/ansible_module_os_recordset.py\", line 172, in main\n    recordsets = cloud.search_recordsets(zone, name_or_id=name + '.' + zone, filters=recordset_filter)\n  File \"/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openstack/cloud/openstackcloud.py\", line 8551, in search_recordsets\n    return _utils._filter_list(recordsets, name_or_id, filters)\n  File \"/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openstack/cloud/_utils.py\", line 113, in _filter_list\n    e_id = _make_unicode(e.get('id', None))\nAttributeError: 'str' object has no attribute 'get'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def _system_state_change(state, records, description, ttl, zone, recordset):
    if state == "present":
        if recordset is None:
            return True
        if records is not None and recordset["records"] != records:
            return True
        if description is not None and recordset["description"] != description:
            return True
        if ttl is not None and recordset["ttl"] != ttl:
            return True
    if state == "absent" and recordset:
        return True
    return False
# Buggy code
def parse_structured_power_supply_info(self, data):
    if data.get("powersup").get("TABLE_psinfo_n3k"):
        data = data["powersup"]["TABLE_psinfo_n3k"]["ROW_psinfo_n3k"]
    else:
        data = data["powersup"]["TABLE_psinfo"]["ROW_psinfo"]
    objects = list(self.transform_iterable(data, self.POWERSUP_MAP))
    return objects


# Traceback (NameError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: global name 'objects' is not defined
fatal: [10.199.95.91]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/g1/5b6mspgs187gcj1lfxtltcz40000gn/T/ansible_ljmRR5/ansible_module_nxos_facts.py\", line 981, in <module>\n    main()\n  File \"/var/folders/g1/5b6mspgs187gcj1lfxtltcz40000gn/T/ansible_ljmRR5/ansible_module_nxos_facts.py\", line 964, in main\n    inst.populate()\n  File \"/var/folders/g1/5b6mspgs187gcj1lfxtltcz40000gn/T/ansible_ljmRR5/ansible_module_nxos_facts.py\", line 749, in populate\n    self.facts['_power_supply_info'] = self.parse_structured_power_supply_info(data)\n  File \"/var/folders/g1/5b6mspgs187gcj1lfxtltcz40000gn/T/ansible_ljmRR5/ansible_module_nxos_facts.py\", line 793, in parse_structured_power_supply_info\n    return objects\nNameError: global name 'objects' is not defined\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def parse_structured_power_supply_info(self, data):
    if data.get("powersup").get("TABLE_psinfo_n3k"):
        fact = data["powersup"]["TABLE_psinfo_n3k"]["ROW_psinfo_n3k"]
    else:
        if isinstance(data["powersup"]["TABLE_psinfo"], list):
            fact = []
            for i in data["powersup"]["TABLE_psinfo"]:
                fact.append(i["ROW_psinfo"])
        else:
            fact = data["powersup"]["TABLE_psinfo"]["ROW_psinfo"]

    objects = list(self.transform_iterable(fact, self.POWERSUP_MAP))
    return objects