gurudesh/pytracebugs huggingface dataset:
# Buggy code
def main():
    argument_spec = dict(
        volume_name=dict(type="str", required=True, aliases=["name"]),
        state=dict(type="str", default="present", choices=["present", "absent"]),
        driver=dict(type="str", default="local"),
        driver_options=dict(type="dict", default={}),
        labels=dict(type="list"),
        force=dict(type="bool", default=False),
        debug=dict(type="bool", default=False),
    )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_version="1.10.0",
        # "The docker server >= 1.9.0"
    )

    cm = DockerVolumeManager(client)
    client.module.exit_json(**cm.results)


# Traceback (TypeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: labels must be a dictionary
fatal: [victorf-C22_qa21]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_FZpuM7/ansible_module_docker_volume.py\", line 254, in <module>\n    main()\n  File \"/tmp/ansible_FZpuM7/ansible_module_docker_volume.py\", line 249, in main\n    cm = DockerVolumeManager(client)\n  File \"/tmp/ansible_FZpuM7/ansible_module_docker_volume.py\", line 142, in __init__\n    self.present()\n  File \"/tmp/ansible_FZpuM7/ansible_module_docker_volume.py\", line 219, in present\n    self.create_volume()\n  File \"/tmp/ansible_FZpuM7/ansible_module_docker_volume.py\", line 191, in create_volume\n    labels=self.parameters.labels)\n  File \"/usr/local/lib/python2.7/dist-packages/docker/utils/decorators.py\", line 35, in wrapper\n    return f(self, *args, **kwargs)\n  File \"/usr/local/lib/python2.7/dist-packages/docker/api/volume.py\", line 32, in create_volume\n    raise TypeError('labels must be a dictionary')\nTypeError: labels must be a dictionary\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def main():
    argument_spec = dict(
        volume_name=dict(type="str", required=True, aliases=["name"]),
        state=dict(type="str", default="present", choices=["present", "absent"]),
        driver=dict(type="str", default="local"),
        driver_options=dict(type="dict", default={}),
        labels=dict(type="dict"),
        force=dict(type="bool", default=False),
        debug=dict(type="bool", default=False),
    )

    client = AnsibleDockerClient(
        argument_spec=argument_spec,
        supports_check_mode=True,
        min_docker_version="1.10.0",
        # "The docker server >= 1.9.0"
    )

    cm = DockerVolumeManager(client)
    client.module.exit_json(**cm.results)
# Buggy code
def _flatpak_command(module, noop, command):
    global result
    if noop:
        result["rc"] = 0
        result["command"] = command
        return ""

    process = subprocess.Popen(
        command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    stdout_data, stderr_data = process.communicate()
    result["rc"] = process.returncode
    result["command"] = command
    result["stdout"] = stdout_data
    result["stderr"] = stderr_data
    if result["rc"] != 0:
        module.fail_json(msg="Failed to execute flatpak command", **result)
    return stdout_data


# Traceback (TypeError)
TASK [gimp : Add the flathub repo] ***********************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: str() takes at most 1 argument (2 given)
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/home/jobevers/.ansible/tmp/ansible-tmp-1539386922.9-194125817113373/AnsiballZ_flatpak_remote.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/home/jobevers/.ansible/tmp/ansible-tmp-1539386922.9-194125817113373/AnsiballZ_flatpak_remote.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/home/jobevers/.ansible/tmp/ansible-tmp-1539386922.9-194125817113373/AnsiballZ_flatpak_remote.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/tmp/ansible_flatpak_remote_payload_W2AKIh/__main__.py\", line 219, in <module>\n  File \"/tmp/ansible_flatpak_remote_payload_W2AKIh/__main__.py\", line 208, in main\nTypeError: str() takes at most 1 argument (2 given)\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def _flatpak_command(module, noop, command):
    global result
    if noop:
        result["rc"] = 0
        result["command"] = command
        return ""

    process = subprocess.Popen(
        command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    stdout_data, stderr_data = process.communicate()
    result["rc"] = process.returncode
    result["command"] = command
    result["stdout"] = stdout_data
    result["stderr"] = stderr_data
    if result["rc"] != 0:
        module.fail_json(msg="Failed to execute flatpak command", **result)
    return to_native(stdout_data)
# Buggy code
def __init__(self, module):
    super(HostVmnicMgr, self).__init__(module)
    cluster_name = self.params.get("cluster_name", None)
    esxi_host_name = self.params.get("esxi_hostname", None)
    self.hosts = self.get_all_host_objs(
        cluster_name=cluster_name, esxi_host_name=esxi_host_name
    )


# Traceback (AttributeError)
PLAY [Host vmnics facts] **********************************************************************************************************************************************************************************************************************************************************

TASK [get ESXi vmincs config] *****************************************************************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'nicDevice'
fatal: [<ESXI HOSTNAME>]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 185, in <module>\n    main()\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 181, in main\n    module.exit_json(changed=False, hosts_vmnics_facts=host_vmnic_mgr.gather_host_vmnic_facts())\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 143, in gather_host_vmnic_facts\n    for vnic in vswitch.spec.bridge.nicDevice:\nAttributeError: 'NoneType' object has no attribute 'nicDevice'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************
<ESXI HOSTNAME> : ok=0    changed=0    unreachable=0    failed=1

# Fixed code
def __init__(self, module):
    super(HostVmnicMgr, self).__init__(module)
    self.capabilities = self.params.get("capabilities")
    self.directpath_io = self.params.get("directpath_io")
    self.sriov = self.params.get("sriov")
    cluster_name = self.params.get("cluster_name", None)
    esxi_host_name = self.params.get("esxi_hostname", None)
    self.hosts = self.get_all_host_objs(
        cluster_name=cluster_name, esxi_host_name=esxi_host_name
    )
    if not self.hosts:
        self.module.fail_json(msg="Failed to find host system.")
# Buggy code
def find_dvs_by_uuid(self, uuid=None):
    dvs_obj = None
    if uuid is None:
        return dvs_obj

    dvswitches = get_all_objs(self.content, [vim.DistributedVirtualSwitch])
    for dvs in dvswitches:
        if dvs.uuid == uuid:
            dvs_obj = dvs
            break

    return dvs_obj


# Traceback (AttributeError)
PLAY [Host vmnics facts] **********************************************************************************************************************************************************************************************************************************************************

TASK [get ESXi vmincs config] *****************************************************************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'nicDevice'
fatal: [<ESXI HOSTNAME>]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 185, in <module>\n    main()\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 181, in main\n    module.exit_json(changed=False, hosts_vmnics_facts=host_vmnic_mgr.gather_host_vmnic_facts())\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 143, in gather_host_vmnic_facts\n    for vnic in vswitch.spec.bridge.nicDevice:\nAttributeError: 'NoneType' object has no attribute 'nicDevice'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************
<ESXI HOSTNAME> : ok=0    changed=0    unreachable=0    failed=1

# Fixed code
def find_dvs_by_uuid(self, uuid=None):
    """Find DVS by it's UUID"""
    dvs_obj = None
    if uuid is None:
        return dvs_obj

    dvswitches = get_all_objs(self.content, [vim.DistributedVirtualSwitch])
    for dvs in dvswitches:
        if dvs.uuid == uuid:
            dvs_obj = dvs
            break

    return dvs_obj
# Buggy code
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        cluster_name=dict(type="str", required=False),
        esxi_hostname=dict(type="str", required=False),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=[
            ["cluster_name", "esxi_hostname"],
        ],
        supports_check_mode=True,
    )

    host_vmnic_mgr = HostVmnicMgr(module)
    module.exit_json(
        changed=False, hosts_vmnics_facts=host_vmnic_mgr.gather_host_vmnic_facts()
    )


# Traceback (AttributeError)
PLAY [Host vmnics facts] **********************************************************************************************************************************************************************************************************************************************************

TASK [get ESXi vmincs config] *****************************************************************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'nicDevice'
fatal: [<ESXI HOSTNAME>]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 185, in <module>\n    main()\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 181, in main\n    module.exit_json(changed=False, hosts_vmnics_facts=host_vmnic_mgr.gather_host_vmnic_facts())\n  File \"/tmp/ansible_U6rTuq/ansible_module_vmware_host_vmnic_facts.py\", line 143, in gather_host_vmnic_facts\n    for vnic in vswitch.spec.bridge.nicDevice:\nAttributeError: 'NoneType' object has no attribute 'nicDevice'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

PLAY RECAP ************************************************************************************************************************************************************************************************************************************************************************
<ESXI HOSTNAME> : ok=0    changed=0    unreachable=0    failed=1

# Fixed code
def main():
    """Main"""
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        cluster_name=dict(type="str", required=False),
        esxi_hostname=dict(type="str", required=False),
        capabilities=dict(type="bool", required=False, default=False),
        directpath_io=dict(type="bool", required=False, default=False),
        sriov=dict(type="bool", required=False, default=False),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=[
            ["cluster_name", "esxi_hostname"],
        ],
        supports_check_mode=True,
    )

    host_vmnic_mgr = HostVmnicMgr(module)
    module.exit_json(
        changed=False, hosts_vmnics_facts=host_vmnic_mgr.gather_host_vmnic_facts()
    )
# Buggy code
def get(self):
    parameters = self._exec(["list_parameters", "-p", self.vhost], True)

    for param_item in parameters:
        component, name, value = param_item.split("\t")

        if component == self.component and name == self.name:
            self._value = json.loads(value)
            return True
    return False


# Traceback (nValueError)
fatal: [test-host]: FAILED! => {"changed": false, "module_stderr": "Shared connection to 10.11.129.20 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/user/0/ansible_niH3aO/ansible_module_rabbitmq_parameter.py\", line 163, in <module>\r\n    main()\r\n  File \"/tmp/user/0/ansible_niH3aO/ansible_module_rabbitmq_parameter.py\", line 144, in main\r\n    if rabbitmq_parameter.get():\r\n  File \"/tmp/user/0/ansible_niH3aO/ansible_module_rabbitmq_parameter.py\", line 96, in get\r\n    component, name, value = param_item.split('\\t')\r\nValueError: need more than 1 value to unpack\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def get(self):
    parameters = [
        param
        for param in self._exec(["list_parameters", "-p", self.vhost], True)
        if param.strip()
    ]

    for param_item in parameters:
        component, name, value = param_item.split("\t")

        if component == self.component and name == self.name:
            self._value = json.loads(value)
            return True
    return False
# Buggy code
def lookup_role_by_name(self, role_name, notify=True):
    """
    Find a role by name.
    """
    role_name = urlquote(role_name)

    try:
        parts = role_name.split(".")
        user_name = ".".join(parts[0:-1])
        role_name = parts[-1]
        if notify:
            display.display(
                "- downloading role '%s', owned by %s" % (role_name, user_name)
            )
    except:
        raise AnsibleError(
            "Invalid role name (%s). Specify role as format: username.rolename"
            % role_name
        )

    url = "%s/roles/?owner__username=%s&name=%s" % (self.baseurl, user_name, role_name)
    data = self.__call_galaxy(url)
    if len(data["results"]) != 0:
        return data["results"][0]
    return None


# Traceback (KeyError)
[notting@nostromo: ~]$ ansible-galaxy -vvv search "🐉🐉🐉"
ansible-galaxy 2.6.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/notting/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-galaxy
python version = 2.7.15 (default, May 16 2018, 17:50:09) [GCC 8.1.1 20180502 (Red Hat 8.1.1-1)]
Using /etc/ansible/ansible.cfg as config file
Opened /home/notting/.ansible_galaxy
ERROR! Unexpected Exception, this is probably a bug: u'\U0001f409'
the full traceback was:

Traceback (most recent call last):
File "/usr/bin/ansible-galaxy", line 118, in <module>
exit_code = cli.run()
File "/usr/lib/python2.7/site-packages/ansible/cli/galaxy.py", line 152, in run
self.execute()
File "/usr/lib/python2.7/site-packages/ansible/cli/__init__.py", line 155, in execute
fn()
File "/usr/lib/python2.7/site-packages/ansible/cli/galaxy.py", line 521, in execute_search
tags=self.options.galaxy_tags, author=self.options.author, page_size=page_size)
File "/usr/lib/python2.7/site-packages/ansible/galaxy/api.py", line 56, in wrapped
return method(self, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/ansible/galaxy/api.py", line 249, in search_roles
search_url += '&amp;autocomplete=' + urlquote(search)
File "/usr/lib64/python2.7/urllib.py", line 1298, in quote
return ''.join(map(quoter, s))
KeyError: u'\U0001f409'

# Fixed code
def lookup_role_by_name(self, role_name, notify=True):
    """
    Find a role by name.
    """
    role_name = to_text(urlquote(to_bytes(role_name)))

    try:
        parts = role_name.split(".")
        user_name = ".".join(parts[0:-1])
        role_name = parts[-1]
        if notify:
            display.display(
                "- downloading role '%s', owned by %s" % (role_name, user_name)
            )
    except:
        raise AnsibleError(
            "Invalid role name (%s). Specify role as format: username.rolename"
            % role_name
        )

    url = "%s/roles/?owner__username=%s&name=%s" % (self.baseurl, user_name, role_name)
    data = self.__call_galaxy(url)
    if len(data["results"]) != 0:
        return data["results"][0]
    return None
# Buggy code
def __init__(self, module):
    self.module = module

    self.state = self.module.params["state"]
    self.host = self.module.params["host"]
    self.backend = self.module.params["backend"]
    self.weight = self.module.params["weight"]
    self.socket = self.module.params["socket"]
    self.shutdown_sessions = self.module.params["shutdown_sessions"]
    self.fail_on_not_found = self.module.params["fail_on_not_found"]
    self.wait = self.module.params["wait"]
    self.wait_retries = self.module.params["wait_retries"]
    self.wait_interval = self.module.params["wait_interval"]
    self.drain = self.module.params["drain"]
    self.command_results = {}


# Traceback (nTypeError)
fatal: [10.5.59.15]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 10.5.59.15 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 454, in <module>\r\n    main()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 450, in main\r\n    ansible_haproxy.act()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 410, in act\r\n    self.drain(self.host, self.backend)\r\nTypeError: 'bool' object is not callable\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def __init__(self, module):
    self.module = module

    self.state = self.module.params["state"]
    self.host = self.module.params["host"]
    self.backend = self.module.params["backend"]
    self.weight = self.module.params["weight"]
    self.socket = self.module.params["socket"]
    self.shutdown_sessions = self.module.params["shutdown_sessions"]
    self.fail_on_not_found = self.module.params["fail_on_not_found"]
    self.wait = self.module.params["wait"]
    self.wait_retries = self.module.params["wait_retries"]
    self.wait_interval = self.module.params["wait_interval"]
    self._drain = self.module.params["drain"]
    self.command_results = {}
# Buggy code
def wait_until_status(self, pxname, svname, status):
    """
    Wait for a service to reach the specified status. Try RETRIES times
    with INTERVAL seconds of sleep in between. If the service has not reached
    the expected status in that time, the module will fail. If the service was
    not found, the module will fail.
    """
    for i in range(1, self.wait_retries):
        state = self.get_state_for(pxname, svname)

        # We can assume there will only be 1 element in state because both svname and pxname are always set when we get here
        if state[0]["status"] == status:
            if not self.drain or (state[0]["scur"] == "0" and state == "MAINT"):
                return True
        else:
            time.sleep(self.wait_interval)

    self.module.fail_json(
        msg="server %s/%s not status '%s' after %d retries. Aborting."
        % (pxname, svname, status, self.wait_retries)
    )


# Traceback (nTypeError)
fatal: [10.5.59.15]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 10.5.59.15 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 454, in <module>\r\n    main()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 450, in main\r\n    ansible_haproxy.act()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 410, in act\r\n    self.drain(self.host, self.backend)\r\nTypeError: 'bool' object is not callable\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def wait_until_status(self, pxname, svname, status):
    """
    Wait for a service to reach the specified status. Try RETRIES times
    with INTERVAL seconds of sleep in between. If the service has not reached
    the expected status in that time, the module will fail. If the service was
    not found, the module will fail.
    """
    for i in range(1, self.wait_retries):
        state = self.get_state_for(pxname, svname)

        # We can assume there will only be 1 element in state because both svname and pxname are always set when we get here
        if state[0]["status"] == status:
            if not self._drain or (state[0]["scur"] == "0" and state == "MAINT"):
                return True
        else:
            time.sleep(self.wait_interval)

    self.module.fail_json(
        msg="server %s/%s not status '%s' after %d retries. Aborting."
        % (pxname, svname, status, self.wait_retries)
    )
# Buggy code
def act(self):
    """
    Figure out what you want to do from ansible, and then do it.
    """
    # Get the state before the run
    state_before = self.get_state_for(self.backend, self.host)
    self.command_results["state_before"] = state_before

    # toggle enable/disbale server
    if self.state == "enabled":
        self.enabled(self.host, self.backend, self.weight)
    elif self.state == "disabled" and self.drain:
        self.drain(self.host, self.backend, status="MAINT")
    elif self.state == "disabled":
        self.disabled(self.host, self.backend, self.shutdown_sessions)
    elif self.state == "drain":
        self.drain(self.host, self.backend)
    else:
        self.module.fail_json(msg="unknown state specified: '%s'" % self.state)

    # Get the state after the run
    state_after = self.get_state_for(self.backend, self.host)
    self.command_results["state_after"] = state_after

    # Report change status
    if state_before != state_after:
        self.command_results["changed"] = True
        self.module.exit_json(**self.command_results)
    else:
        self.command_results["changed"] = False
        self.module.exit_json(**self.command_results)


# Traceback (nTypeError)
fatal: [10.5.59.15]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 10.5.59.15 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 454, in <module>\r\n    main()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 450, in main\r\n    ansible_haproxy.act()\r\n  File \"/tmp/ansible_Xzs48s/ansible_module_haproxy.py\", line 410, in act\r\n    self.drain(self.host, self.backend)\r\nTypeError: 'bool' object is not callable\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def act(self):
    """
    Figure out what you want to do from ansible, and then do it.
    """
    # Get the state before the run
    state_before = self.get_state_for(self.backend, self.host)
    self.command_results["state_before"] = state_before

    # toggle enable/disbale server
    if self.state == "enabled":
        self.enabled(self.host, self.backend, self.weight)
    elif self.state == "disabled" and self._drain:
        self.drain(self.host, self.backend, status="MAINT")
    elif self.state == "disabled":
        self.disabled(self.host, self.backend, self.shutdown_sessions)
    elif self.state == "drain":
        self.drain(self.host, self.backend)
    else:
        self.module.fail_json(msg="unknown state specified: '%s'" % self.state)

    # Get the state after the run
    state_after = self.get_state_for(self.backend, self.host)
    self.command_results["state_after"] = state_after

    # Report change status
    if state_before != state_after:
        self.command_results["changed"] = True
        self.module.exit_json(**self.command_results)
    else:
        self.command_results["changed"] = False
        self.module.exit_json(**self.command_results)
# Buggy code
def check_current_entry(module):
    # Check if entry exists, if not return False in exists in return dict,
    # if true return True and the entry in return dict
    existsdict = {"exist": False}
    lsitab = module.get_bin_path("lsitab")
    (rc, out, err) = module.run_command([lsitab, module.params["name"]])
    if rc == 0:
        keys = ("name", "runlevel", "action", "command")
        values = out.split(":")
        # strip non readable characters as \n
        values = map(lambda s: s.strip(), values)
        existsdict = dict(itertools.izip(keys, values))
        existsdict.update({"exist": True})
    return existsdict


# Traceback (nAttributeError)
fatal: [aixtest01]: FAILED! => {
"changed": false,
"module_stderr": "OpenSSH_7.7p1, OpenSSL 1.0.2o  27 Mar 2018\r\ndebug1: Reading configuration data /home/trustchk/.ssh/config\r\ndebug1: /home/trustchk/.ssh/config line 23: Applying options for aix*\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 8811\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 1\r\nShared connection to aixtest01 closed.\r\n",
"module_stdout": "\r\nTraceback (most recent call last):\r\n  File \"/tmp/ansible_13e6hkx0/ansible_module_aix_inittab.py\", line 241, in <module>\r\n    main()\r\n  File \"/tmp/ansible_13e6hkx0/ansible_module_aix_inittab.py\", line 184, in main\r\n    current_entry = check_current_entry(module)\r\n  File \"/tmp/ansible_13e6hkx0/ansible_module_aix_inittab.py\", line 139, in check_current_entry\r\n    existsdict = dict(itertools.izip(keys, values))\r\nAttributeError: module 'itertools' has no attribute 'izip'\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def check_current_entry(module):
    # Check if entry exists, if not return False in exists in return dict,
    # if true return True and the entry in return dict
    existsdict = {"exist": False}
    lsitab = module.get_bin_path("lsitab")
    (rc, out, err) = module.run_command([lsitab, module.params["name"]])
    if rc == 0:
        keys = ("name", "runlevel", "action", "command")
        values = out.split(":")
        # strip non readable characters as \n
        values = map(lambda s: s.strip(), values)
        existsdict = dict(izip(keys, values))
        existsdict.update({"exist": True})
    return existsdict
# Buggy code
def _get_quotas(sdk, module, cloud, project):
    quota = {}
    try:
        quota["volume"] = _get_volume_quotas(cloud, project)
    except sdk.exceptions.OpenStackCloudURINotFound:
        module.warn(
            "No public endpoint for volumev2 service was found. Ignoring volume quotas."
        )

    try:
        quota["network"] = _get_network_quotas(cloud, project)
    except sdk.exceptions.OpenStackCloudURINotFound:
        module.warn(
            "No public endpoint for network service was found. Ignoring network quotas."
        )

    quota["compute"] = _get_compute_quotas(cloud, project)

    for quota_type in quota.keys():
        quota[quota_type] = _scrub_results(quota[quota_type])

    return quota


# Traceback (AttributeError)
TASK [Destroy test volume] ********************************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'OpenStackCloudTimeout'
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 168, in <module>\n    main()\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 162, in main\n    _absent_volume(module, cloud, sdk)\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 127, in _absent_volume\n    except sdk.exceptions.OpenStackCloudTimeout:\nAttributeError: 'module' object has no attribute 'OpenStackCloudTimeout'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
to retry, use: --limit @/home/dcarrillo/datio/iluvatar/deployer/ansible/roles/tools/backup/snapshots/molecule/default/destroy.retry

# Fixed code
def _get_quotas(sdk, module, cloud, project):
    quota = {}
    try:
        quota["volume"] = _get_volume_quotas(cloud, project)
    except sdk.exceptions.NotFoundException:
        module.warn(
            "No public endpoint for volumev2 service was found. Ignoring volume quotas."
        )

    try:
        quota["network"] = _get_network_quotas(cloud, project)
    except sdk.exceptions.NotFoundException:
        module.warn(
            "No public endpoint for network service was found. Ignoring network quotas."
        )

    quota["compute"] = _get_compute_quotas(cloud, project)

    for quota_type in quota.keys():
        quota[quota_type] = _scrub_results(quota[quota_type])

    return quota
# Buggy code
def _absent_volume(module, cloud, sdk):
    changed = False
    if cloud.volume_exists(module.params["display_name"]):
        try:
            changed = cloud.delete_volume(
                name_or_id=module.params["display_name"],
                wait=module.params["wait"],
                timeout=module.params["timeout"],
            )
        except sdk.exceptions.OpenStackCloudTimeout:
            module.exit_json(changed=changed)

    module.exit_json(changed=changed)


# Traceback (AttributeError)
TASK [Destroy test volume] ********************************************************************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'OpenStackCloudTimeout'
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 168, in <module>\n    main()\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 162, in main\n    _absent_volume(module, cloud, sdk)\n  File \"/tmp/ansible_6aYn_b/ansible_module_os_volume.py\", line 127, in _absent_volume\n    except sdk.exceptions.OpenStackCloudTimeout:\nAttributeError: 'module' object has no attribute 'OpenStackCloudTimeout'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
to retry, use: --limit @/home/dcarrillo/datio/iluvatar/deployer/ansible/roles/tools/backup/snapshots/molecule/default/destroy.retry

# Fixed code
def _absent_volume(module, cloud, sdk):
    changed = False
    if cloud.volume_exists(module.params["display_name"]):
        try:
            changed = cloud.delete_volume(
                name_or_id=module.params["display_name"],
                wait=module.params["wait"],
                timeout=module.params["timeout"],
            )
        except sdk.exceptions.ResourceTimeout:
            module.exit_json(changed=changed)

    module.exit_json(changed=changed)
# Buggy code
def index_of_matching_route(route_spec, routes_to_match):
    for i, route in enumerate(routes_to_match):
        if route_spec_matches_route(route_spec, route):
            return "exact", i
        elif route_spec_matches_route_cidr(route_spec, route):
            return "replace", i


# Traceback (ClientError)
TASK [Set up private subnet route table] ********************************************************************************************************************************************************************************************
task path: /home/dse09/src/vtp-aws-infra/test2.yml:18
Using module file /usr/lib/python2.7/site-packages/ansible/modules/cloud/amazon/ec2_vpc_route_table.py
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: dse09
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_f7ocmU/ansible_module_ec2_vpc_route_table.py", line 481, in ensure_routes
**route_spec)
File "/usr/lib/python2.7/site-packages/botocore/client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/lib/python2.7/site-packages/botocore/client.py", line 612, in _make_api_call
raise error_class(parsed_response, operation_name)
ClientError: An error occurred (InvalidParameterValue) when calling the ReplaceRoute operation: There is no route defined for '10.50.27.0/24' in the route table. Use CreateRoute instead.

fatal: [localhost]: FAILED! => {
"boto3_version": "1.4.6",
"botocore_version": "1.10.30",
"changed": false,
"error": {
"code": "InvalidParameterValue",
"message": "There is no route defined for '10.50.27.0/24' in the route table. Use CreateRoute instead."
},
"invocation": {
"module_args": {
"aws_access_key": "xxx",
"aws_secret_key": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"ec2_url": null,
"lookup": "tag",
"profile": null,
"propagating_vgw_ids": [
"vgw-xxx"
],
"purge_routes": true,
"purge_subnets": true,
"purge_tags": false,
"region": "eu-west-1",
"route_table_id": null,
"routes": [
{
"destination_cidr_block": "10.50.27.0/24",
"vpc_peering_connection_id": "pcx-xxx"
}
],
"security_token": null,
"state": "present",
"subnets": null,
"tags": {
"Name": "stage-private-rt"
},
"validate_certs": true,
"vpc_id": "vpc-xxx"
}
},
"msg": "Couldn't recreate route: An error occurred (InvalidParameterValue) when calling the ReplaceRoute operation: There is no route defined for '10.50.27.0/24' in the route table. Use CreateRoute instead.",
"response_metadata": {
"http_headers": {
"connection": "close",
"date": "Mon, 30 Jul 2018 09:11:05 GMT",
"server": "AmazonEC2",
"transfer-encoding": "chunked"
},
"http_status_code": 400,
"request_id": "c63eac49-4bd8-4a56-b4d6-76273e16ae40",
"retry_attempts": 0
}
}

# Fixed code
def index_of_matching_route(route_spec, routes_to_match):
    for i, route in enumerate(routes_to_match):
        if route_spec_matches_route(route_spec, route):
            return "exact", i
        elif (
            "Origin" in route_spec
            and route_spec["Origin"] != "EnableVgwRoutePropagation"
        ):
            if route_spec_matches_route_cidr(route_spec, route):
                return "replace", i
# Buggy code
def list_origin_access_identities(self):
    try:
        paginator = self.client.get_paginator(
            "list_cloud_front_origin_access_identities"
        )
        result = paginator.paginate().build_full_result()[
            "CloudFrontOriginAccessIdentityList"
        ]
        return result.get("Items", [])
    except botocore.exceptions.ClientError as e:
        self.module.fail_json_aws(
            e, msg="Error listing cloud front origin access identities"
        )


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py", line 284, in <module>
main()
File "/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py", line 262, in main
origin_access_identity_id = validation_mgr.validate_origin_access_identity_id_from_caller_reference(caller_reference)
File "/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py", line 221, in validate_origin_access_identity_id_from_caller_reference
origin_access_identities = self.__cloudfront_facts_mgr.list_origin_access_identities()
File "/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_modlib.zip/ansible/module_utils/aws/cloudfront_facts.py", line 96, in list_origin_access_identities
KeyError: 'CloudFrontOriginAccessIdentityList'

fatal: [localhost]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py\", line 284, in <module>\n  main()\n  File \"/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py\", line 262, in main\n    origin_access_identity_id = validation_mgr.validate_origin_access_identity_id_from_caller_reference(caller_reference)\n  File \"/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_module_cloudfront_origin_access_identity.py\", line 221, in validate_origin_access_identity_id_from_caller_reference\n    origin_access_identities = self.__cloudfront_facts_mgr.list_origin_access_identities()\n  File \"/var/folders/w2/9tfn65155qxfkh2d8r_hhq5c0000gn/T/ansible_MCbyGf/ansible_modlib.zip/ansible/module_utils/aws/cloudfront_facts.py\", line 96, in list_origin_access_identities\nKeyError: 'CloudFrontOriginAccessIdentityList'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def list_origin_access_identities(self):
    try:
        paginator = self.client.get_paginator(
            "list_cloud_front_origin_access_identities"
        )
        result = (
            paginator.paginate()
            .build_full_result()
            .get("CloudFrontOriginAccessIdentityList", {})
        )
        return result.get("Items", [])
    except botocore.exceptions.ClientError as e:
        self.module.fail_json_aws(
            e, msg="Error listing cloud front origin access identities"
        )
# Buggy code
def compile_roles_handlers(self):
    """
    Handles the role handler compilation step, returning a flat list of Handlers
    This is done for all roles in the Play.
    """

    block_list = []

    if len(self.roles) > 0:
        for r in self.roles:
            block_list.extend(r.get_handler_blocks(play=self))

    return block_list


# Traceback (KeyError)
ERROR! Unexpected Exception, this is probably a bug: 'role1'
the full traceback was:

Traceback (most recent call last):
File "ansible/bin/ansible-playbook", line 118, in <module>
exit_code = cli.run()
File "ansible/lib/ansible/cli/playbook.py", line 122, in run
results = pbex.run()
File "ansible/lib/ansible/executor/playbook_executor.py", line 156, in run
result = self._tqm.run(play=play)
File "ansible/lib/ansible/executor/task_queue_manager.py", line 291, in run
play_return = strategy.run(iterator, play_context)
File "ansible/lib/ansible/plugins/strategy/linear.py", line 267, in run
results.extend(self._execute_meta(task, play_context, iterator, host))
File "ansible/lib/ansible/plugins/strategy/__init__.py", line 1031, in _execute_meta
self.run_handlers(iterator, play_context)
File "/home/lilou/src/ansible/ansible.git/lib/ansible/plugins/strategy/__init__.py", line 885, in run_handlers
result = self._do_handler_run(handler, handler_name, iterator=iterator, play_context=play_context)
File "ansible/lib/ansible/plugins/strategy/__init__.py", line 928, in _do_handler_run
host_results = self._wait_on_handler_results(iterator, handler, notified_hosts)
File "ansible/lib/ansible/plugins/strategy/__init__.py", line 686, in _wait_on_handler_results
results = self._process_pending_results(iterator)
File "ansible/lib/ansible/plugins/strategy/__init__.py", line 117, in inner
results = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
File "ansible/lib/ansible/plugins/strategy/__init__.py", line 656, in _process_pending_results
for (entry, role_obj) in iteritems(iterator._play.ROLE_CACHE[original_task._role._role_name]):
KeyError: 'role1'

# Fixed code
def compile_roles_handlers(self):
    """
    Handles the role handler compilation step, returning a flat list of Handlers
    This is done for all roles in the Play.
    """

    block_list = []

    if len(self.roles) > 0:
        for r in self.roles:
            if r.from_include:
                continue
            block_list.extend(r.get_handler_blocks(play=self))

    return block_list
# Buggy code
def decrypt_file(self, filename, output_file=None):
    # follow the symlink
    filename = self._real_path(filename)

    ciphertext = self.read_data(filename)

    try:
        plaintext = self.vault.decrypt(ciphertext, filename=filename)
    except AnsibleError as e:
        raise AnsibleError("%s for %s" % (to_bytes(e), to_bytes(filename)))
    self.write_data(plaintext, output_file or filename, shred=False)


# Traceback (OSError)
ansible-vault 2.6.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/the-noob/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-vault
python version = 2.7.12 (default, Dec  4 2017, 14:50:18) [GCC 5.4.0 20160609]
Using /etc/ansible/ansible.cfg as config file
Vault password:
ERROR! Unexpected Exception, this is probably a bug: [Errno 2] No such file or directory
the full traceback was:

Traceback (most recent call last):
File "/usr/bin/ansible-vault", line 118, in <module>
exit_code = cli.run()
File "/usr/lib/python2.7/dist-packages/ansible/cli/vault.py", line 255, in run
self.execute()
File "/usr/lib/python2.7/dist-packages/ansible/cli/__init__.py", line 155, in execute
fn()
File "/usr/lib/python2.7/dist-packages/ansible/cli/vault.py", line 446, in execute_edit
self.editor.edit_file(f)
File "/usr/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 975, in edit_file
force_save=False, vault_id=vault_id)
File "/usr/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 864, in _edit_file_helper
subprocess.call(self._editor_shell_command(tmp_path))
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def decrypt_file(self, filename, output_file=None):
    # follow the symlink
    filename = self._real_path(filename)

    ciphertext = self.read_data(filename)

    try:
        plaintext = self.vault.decrypt(ciphertext, filename=filename)
    except AnsibleError as e:
        raise AnsibleError("%s for %s" % (to_native(e), to_native(filename)))
    self.write_data(plaintext, output_file or filename, shred=False)
# Buggy code
def plaintext(self, filename):
    b_vaulttext = self.read_data(filename)
    vaulttext = to_text(b_vaulttext)

    try:
        plaintext = self.vault.decrypt(vaulttext, filename=filename)
        return plaintext
    except AnsibleError as e:
        raise AnsibleVaultError("%s for %s" % (to_bytes(e), to_bytes(filename)))


# Traceback (OSError)
ansible-vault 2.6.3
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/the-noob/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-vault
python version = 2.7.12 (default, Dec  4 2017, 14:50:18) [GCC 5.4.0 20160609]
Using /etc/ansible/ansible.cfg as config file
Vault password:
ERROR! Unexpected Exception, this is probably a bug: [Errno 2] No such file or directory
the full traceback was:

Traceback (most recent call last):
File "/usr/bin/ansible-vault", line 118, in <module>
exit_code = cli.run()
File "/usr/lib/python2.7/dist-packages/ansible/cli/vault.py", line 255, in run
self.execute()
File "/usr/lib/python2.7/dist-packages/ansible/cli/__init__.py", line 155, in execute
fn()
File "/usr/lib/python2.7/dist-packages/ansible/cli/vault.py", line 446, in execute_edit
self.editor.edit_file(f)
File "/usr/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 975, in edit_file
force_save=False, vault_id=vault_id)
File "/usr/lib/python2.7/dist-packages/ansible/parsing/vault/__init__.py", line 864, in _edit_file_helper
subprocess.call(self._editor_shell_command(tmp_path))
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def plaintext(self, filename):
    b_vaulttext = self.read_data(filename)
    vaulttext = to_text(b_vaulttext)

    try:
        plaintext = self.vault.decrypt(vaulttext, filename=filename)
        return plaintext
    except AnsibleError as e:
        raise AnsibleVaultError("%s for %s" % (to_native(e), to_native(filename)))
# Buggy code
def vlan_range_to_list(vlans):
    result = []
    if vlans:
        for part in vlans.split(","):
            if part.lower() == "none":
                break
            if "-" in part:
                start, stop = (int(i) for i in part.split("-"))
                result.extend(range(start, stop + 1))
            else:
                result.append(int(part))
    return sorted(result)


# Traceback (ValueError)
def vlan_range_to_list(vlans):
...     result = []
...     if vlans:
...         for part in vlans.split(','):
...             if part.lower() == 'none':
...                 break
...             if '-' in part:
...                 start, stop = (int(i) for i in part.split('-'))
...                 result.extend(range(start, stop + 1))
...             else:
...                 result.append(int(part))
...     return sorted(result)
...
vlans = "228-230,370,378,379,381,385,500,501,580-584,600,646,"
vlan_range_to_list(vlans)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in vlan_range_to_list
ValueError: invalid literal for int() with base 10: ''
vlans = "228-230,370,378,379,381,385,500,501,580-584,600,646"
vlan_range_to_list(vlans)
[228, 229, 230, 370, 378, 379, 381, 385, 500, 501, 580, 581, 582, 583, 584, 600, 646]


# Fixed code
def vlan_range_to_list(vlans):
    result = []
    if vlans:
        for part in vlans.split(","):
            if part.lower() == "none":
                break
            if part:
                if "-" in part:
                    start, stop = (int(i) for i in part.split("-"))
                    result.extend(range(start, stop + 1))
                else:
                    result.append(int(part))
    return sorted(result)