gurudesh/pytracebugs huggingface dataset:
# Buggy code
def modify_connection_ethernet(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for  modifying ethernet interface
    # To add an Ethernet connection with static IP configuration, issue a command as follows
    # - nmcli: name=add conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
    # nmcli con add con-name my-eth1 ifname eth1 type ethernet ip4 192.0.2.100/24 gw4 192.0.2.1
    cmd.append("con")
    cmd.append("mod")
    cmd.append(self.conn_name)
    if self.ip4 is not None:
        cmd.append("ipv4.address")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("ipv4.gateway")
        cmd.append(self.gw4)
    if self.dns4 is not None:
        cmd.append("ipv4.dns")
        cmd.append(self.dns4)
    if self.ip6 is not None:
        cmd.append("ipv6.address")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("ipv6.gateway")
        cmd.append(self.gw6)
    if self.dns6 is not None:
        cmd.append("ipv6.dns")
        cmd.append(self.dns6)
    if self.mtu is not None:
        cmd.append("802-3-ethernet.mtu")
        cmd.append(self.mtu)
    if self.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
    return cmd


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def modify_connection_ethernet(self):
    cmd = [self.nmcli_bin, "con", "mod", self.conn_name]
    # format for  modifying ethernet interface
    # To add an Ethernet connection with static IP configuration, issue a command as follows
    # - nmcli: name=add conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
    # nmcli con add con-name my-eth1 ifname eth1 type ethernet ip4 192.0.2.100/24 gw4 192.0.2.1
    if self.ip4 is not None:
        cmd.append("ipv4.address")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("ipv4.gateway")
        cmd.append(self.gw4)
    if self.dns4 is not None:
        cmd.append("ipv4.dns")
        cmd.append(self.dns4)
    if self.ip6 is not None:
        cmd.append("ipv6.address")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("ipv6.gateway")
        cmd.append(self.gw6)
    if self.dns6 is not None:
        cmd.append("ipv6.dns")
        cmd.append(self.dns6)
    if self.mtu is not None:
        cmd.append("802-3-ethernet.mtu")
        cmd.append(self.mtu)
    if self.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
    return cmd
# Buggy code
def create_connection_bridge(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating bridge interface
    return cmd


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def create_connection_bridge(self):
    cmd = [self.nmcli_bin]
    # format for creating bridge interface
    return cmd
# Buggy code
def modify_connection_bridge(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying bridge interface
    return cmd


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def modify_connection_bridge(self):
    cmd = [self.nmcli_bin]
    # format for modifying bridge interface
    return cmd
# Buggy code
def create_connection_vlan(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating ethernet interface
    return cmd


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def create_connection_vlan(self):
    cmd = [self.nmcli_bin]
    # format for creating ethernet interface
    return cmd
# Buggy code
def modify_connection_vlan(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying ethernet interface
    return cmd


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def modify_connection_vlan(self):
    cmd = [self.nmcli_bin]
    # format for modifying ethernet interface
    return cmd
# Buggy code
def remove_connection(self):
    # self.down_connection()
    cmd = [self.module.get_bin_path("nmcli", True)]
    cmd.append("con")
    cmd.append("del")
    cmd.append(self.conn_name)
    return self.execute_command(cmd)


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def remove_connection(self):
    # self.down_connection()
    cmd = [self.nmcli_bin, "con", "del", self.conn_name]
    return self.execute_command(cmd)
# Buggy code
def modify_connection(self):
    cmd = []
    if self.type == "team":
        cmd = self.modify_connection_team()
    elif self.type == "team-slave":
        cmd = self.modify_connection_team_slave()
    elif self.type == "bond":
        cmd = self.modify_connection_bond()
    elif self.type == "bond-slave":
        cmd = self.modify_connection_bond_slave()
    elif self.type == "ethernet":
        cmd = self.modify_connection_ethernet()
    elif self.type == "bridge":
        cmd = self.modify_connection_bridge()
    elif self.type == "vlan":
        cmd = self.modify_connection_vlan()
    return self.execute_command(cmd)


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_cTdlxy/ansible_modlib.zip/ansible/module_utils/basic.py", line 2736, 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 1207, in _execute_child
executable = args[0]
IndexError: list index out of range

# Fixed code
def modify_connection(self):
    cmd = []
    if self.type == "team":
        cmd = self.modify_connection_team()
    elif self.type == "team-slave":
        cmd = self.modify_connection_team_slave()
    elif self.type == "bond":
        cmd = self.modify_connection_bond()
    elif self.type == "bond-slave":
        cmd = self.modify_connection_bond_slave()
    elif self.type == "ethernet":
        cmd = self.modify_connection_ethernet()
    elif self.type == "bridge":
        cmd = self.modify_connection_bridge()
    elif self.type == "vlan":
        cmd = self.modify_connection_vlan()
    if cmd:
        return self.execute_command(cmd)
    else:
        self.module.fail_json(
            msg="Type of device or network connection is required "
            "while performing 'modify' operation. Please specify 'type' as an argument."
        )
# Buggy code
def create_connection_bridge(self):
    cmd = [self.nmcli_bin]
    # format for creating bridge interface
    return cmd


# Traceback (nTypeError)
failed: [sqlmaster1] (item={u'ip4': u'10.0.3.27/24', u'dev': u'ens224'}) => {"changed": false, "failed": true, "item": {"dev": "ens224", "ip4": "10.0.3.27/24"}, "module_stderr": "BECOME-SUCCESS-geacueqlzcdnmgrvmmrmkvmraxfijkly\r\n", "module_stdout": "/tmp/ansible_PpATO0/ansible_module_nmcli.py:493: PyGIWarning: NetworkManager was imported without specifying a version first. Use gi.require_version('NetworkManager', '1.0') before import to ensure that the right version gets loaded.\r\n  from gi.repository import NetworkManager, NMClient\r\n/tmp/ansible_PpATO0/ansible_module_nmcli.py:493: PyGIWarning: NMClient was imported without specifying a version first. Use gi.require_version('NMClient', '1.0') before import to ensure that the right version gets loaded.\r\n  from gi.repository import NetworkManager, NMClient\r\nTraceback (most recent call last):\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 1190, in <module>\r\n    main()\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 1134, in main\r\n    nmcli=Nmcli(module)\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 559, in __init__\r\n    self.dns4=' '.join(module.params['dns4'])\r\nTypeError\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def create_connection_bridge(self):
    # format for creating bridge interface
    # To add an Bridge connection with static IP configuration, issue a command as follows
    # - nmcli: name=add conn_name=my-eth1 ifname=eth1 type=bridge ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
    # nmcli con add con-name my-eth1 ifname eth1 type bridge ip4 192.0.2.100/24 gw4 192.0.2.1
    cmd = [self.nmcli_bin, "con", "add", "type", "bridge", "con-name"]
    if self.conn_name is not None:
        cmd.append(self.conn_name)
    elif self.ifname is not None:
        cmd.append(self.ifname)
    cmd.append("ifname")
    if self.ifname is not None:
        cmd.append(self.ifname)
    elif self.conn_name is not None:
        cmd.append(self.conn_name)

    options = {
        "ip4": self.ip4,
        "gw4": self.gw4,
        "ip6": self.ip6,
        "gw6": self.gw6,
        "autoconnect": self.bool_to_string(self.autoconnect),
        "bridge.ageing-time": self.ageingtime,
        "bridge.forward-delay": self.forwarddelay,
        "bridge.hello-time": self.hellotime,
        "bridge.mac-address": self.mac,
        "bridge.max-age": self.maxage,
        "bridge.priority": self.priority,
        "bridge.stp": self.bool_to_string(self.stp),
    }

    for key, value in options.items():
        if value is not None:
            cmd.extend([key, value])

    return cmd
# Buggy code
def modify_connection_bridge(self):
    cmd = [self.nmcli_bin]
    # format for modifying bridge interface
    return cmd


# Traceback (nTypeError)
failed: [sqlmaster1] (item={u'ip4': u'10.0.3.27/24', u'dev': u'ens224'}) => {"changed": false, "failed": true, "item": {"dev": "ens224", "ip4": "10.0.3.27/24"}, "module_stderr": "BECOME-SUCCESS-geacueqlzcdnmgrvmmrmkvmraxfijkly\r\n", "module_stdout": "/tmp/ansible_PpATO0/ansible_module_nmcli.py:493: PyGIWarning: NetworkManager was imported without specifying a version first. Use gi.require_version('NetworkManager', '1.0') before import to ensure that the right version gets loaded.\r\n  from gi.repository import NetworkManager, NMClient\r\n/tmp/ansible_PpATO0/ansible_module_nmcli.py:493: PyGIWarning: NMClient was imported without specifying a version first. Use gi.require_version('NMClient', '1.0') before import to ensure that the right version gets loaded.\r\n  from gi.repository import NetworkManager, NMClient\r\nTraceback (most recent call last):\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 1190, in <module>\r\n    main()\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 1134, in main\r\n    nmcli=Nmcli(module)\r\n  File \"/tmp/ansible_PpATO0/ansible_module_nmcli.py\", line 559, in __init__\r\n    self.dns4=' '.join(module.params['dns4'])\r\nTypeError\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def modify_connection_bridge(self):
    # format for modifying bridge interface
    # To add an Bridge connection with static IP configuration, issue a command as follows
    # - nmcli: name=mod conn_name=my-eth1 ifname=eth1 type=bridge ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
    # nmcli con mod my-eth1 ifname eth1 type bridge ip4 192.0.2.100/24 gw4 192.0.2.1
    cmd = [self.nmcli_bin, "con", "mod", self.conn_name]

    options = {
        "ip4": self.ip4,
        "gw4": self.gw4,
        "ip6": self.ip6,
        "gw6": self.gw6,
        "autoconnect": self.bool_to_string(self.autoconnect),
        "bridge.ageing-time": self.ageingtime,
        "bridge.forward-delay": self.forwarddelay,
        "bridge.hello-time": self.hellotime,
        "bridge.mac-address": self.mac,
        "bridge.max-age": self.maxage,
        "bridge.priority": self.priority,
        "bridge.stp": self.bool_to_string(self.stp),
    }

    for key, value in options.items():
        if value is not None:
            cmd.extend([key, value])

    return cmd
# Buggy code
def _get_shebang(interpreter, task_vars, args=tuple()):
    """
    Note not stellar API:
       Returns None instead of always returning a shebang line.  Doing it this
       way allows the caller to decide to use the shebang it read from the
       file rather than trust that we reformatted what they already have
       correctly.
    """
    interpreter_config = (
        "ansible_%s_interpreter" % os.path.basename(interpreter).strip()
    )

    if interpreter_config not in task_vars:
        return (None, interpreter)

    interpreter = task_vars[interpreter_config].strip()
    shebang = "#!" + interpreter

    if args:
        shebang = shebang + " " + " ".join(args)

    return (shebang, interpreter)


# Traceback (ImportError)
$ python /Users/will/.ansible/tmp/ansible-tmp-1480409869.55-272491715446155/rds_instance.py execute
Traceback (most recent call last):
File "/Users/will/.ansible/tmp/ansible-tmp-1480409869.55-272491715446155/debug_dir/ansible_module_rds_instance.py", line 710, in <module>
main()
File "/Users/will/.ansible/tmp/ansible-tmp-1480409869.55-272491715446155/debug_dir/ansible_module_rds_instance.py", line 678, in main
import epdb
ImportError: No module named epdb

# Fixed code
def _get_shebang(interpreter, task_vars, templar, args=tuple()):
    """
    Note not stellar API:
       Returns None instead of always returning a shebang line.  Doing it this
       way allows the caller to decide to use the shebang it read from the
       file rather than trust that we reformatted what they already have
       correctly.
    """
    interpreter_config = (
        "ansible_%s_interpreter" % os.path.basename(interpreter).strip()
    )

    if interpreter_config not in task_vars:
        return (None, interpreter)

    interpreter = templar.template(task_vars[interpreter_config].strip())
    shebang = "#!" + interpreter

    if args:
        shebang = shebang + " " + " ".join(args)

    return (shebang, interpreter)
# Buggy code
def _parse_account_key(self, key):
    """
    Parses an RSA key file in PEM format and returns the modulus
    and public exponent of the key
    """
    openssl_keydump_cmd = [self._openssl_bin, "rsa", "-in", key, "-noout", "-text"]
    _, out, _ = self.module.run_command(openssl_keydump_cmd, check_rc=True)

    pub_hex, pub_exp = re.search(
        r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)",
        out.decode("utf8"),
        re.MULTILINE | re.DOTALL,
    ).groups()
    pub_exp = "{0:x}".format(int(pub_exp))
    if len(pub_exp) % 2:
        pub_exp = "0{0}".format(pub_exp)

    return pub_hex, pub_exp


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 812, in <module>
main()
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 802, in main
client = ACMEClient(module)
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 521, in __init__
self.account = ACMEAccount(module)
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 316, in __init__
self.directory = ACMEDirectory(module)
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 289, in __init__
self.directory = simple_get(self.module, self.directory_root)
File "/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py", line 191, in simple_get
if info['content-type'].startswith('application/json'):
KeyError: 'content-type'

fatal: [default]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 812, in <module>\n    main()\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 802, in main\n    client = ACMEClient(module)\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 521, in __init__\n    self.account = ACMEAccount(module)\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 316, in __init__\n    self.directory = ACMEDirectory(module)\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 289, in __init__\n    self.directory = simple_get(self.module, self.directory_root)\n  File \"/tmp/ansible_f44oyk38/ansible_module_letsencrypt.py\", line 191, in simple_get\n    if info['content-type'].startswith('application/json'):\nKeyError: 'content-type'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def _parse_account_key(self, key):
    """
    Parses an RSA key file in PEM format and returns the modulus
    and public exponent of the key
    """
    openssl_keydump_cmd = [self._openssl_bin, "rsa", "-in", key, "-noout", "-text"]
    _, out, _ = self.module.run_command(openssl_keydump_cmd, check_rc=True)

    pub_hex, pub_exp = re.search(
        r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)",
        to_text(out, errors="surrogate_or_strict"),
        re.MULTILINE | re.DOTALL,
    ).groups()
    pub_exp = "{0:x}".format(int(pub_exp))
    if len(pub_exp) % 2:
        pub_exp = "0{0}".format(pub_exp)

    return pub_hex, pub_exp
# Buggy code
def __init__(self, module):
    super(PrivateKey, self).__init__(
        module.params["path"],
        module.params["state"],
        module.params["force"],
        module.check_mode,
    )
    self.size = module.params["size"]
    self.passphrase = module.params["passphrase"]
    self.cipher = module.params["cipher"]
    self.privatekey = None
    self.fingerprint = {}

    self.mode = module.params["mode"]
    if not self.mode:
        self.mode = int("0600", 8)

    self.type = crypto.TYPE_RSA
    if module.params["type"] == "DSA":
        self.type = crypto.TYPE_DSA


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py", line 301, in <module>
main()
File "/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py", line 280, in main
private_key.generate(module)
File "/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py", line 182, in generate
self.mode)
TypeError: an integer is required

fatal: [rded.nl -> localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py\", line 301, in <module>\n    main()\n  File \"/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py\", line 280, in main\n    private_key.generate(module)\n  File \"/tmp/ansible_WIfdnp/ansible_module_openssl_privatekey.py\", line 182, in generate\n    self.mode)\nTypeError: an integer is required\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def __init__(self, module):
    super(PrivateKey, self).__init__(
        module.params["path"],
        module.params["state"],
        module.params["force"],
        module.check_mode,
    )
    self.size = module.params["size"]
    self.passphrase = module.params["passphrase"]
    self.cipher = module.params["cipher"]
    self.privatekey = None
    self.fingerprint = {}

    self.mode = module.params.get("mode", None)
    if self.mode is None:
        self.mode = 0o600

    self.type = crypto.TYPE_RSA
    if module.params["type"] == "DSA":
        self.type = crypto.TYPE_DSA
# Buggy code
def run_command(command):
    """Runs a monit command, and returns the new status."""
    module.run_command("%s %s %s" % (MONIT, command, name), check_rc=True)
    return status()


# Traceback (nTypeError)
fatal: [myhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to myhostclosed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 218, in <module>\r\n    main()\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 164, in main\r\n    wait_for_monit_to_stop_pending()\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 127, in wait_for_monit_to_stop_pending\r\n    running_status = status()\r\nTypeError: 'str' object is not callable\r\n", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/johan/ansible/only_collectd.retry

# Fixed code
def run_command(command):
    """Runs a monit command, and returns the new status."""
    module.run_command("%s %s %s" % (MONIT, command, name), check_rc=True)
    return get_status()
# Buggy code
def wait_for_monit_to_stop_pending():
    """Fails this run if there is no status or it's pending/initializing for timeout"""
    timeout_time = time.time() + timeout
    sleep_time = 5

    running_status = status()
    while (
        running_status == ""
        or "pending" in running_status
        or "initializing" in running_status
    ):
        if time.time() >= timeout_time:
            module.fail_json(
                msg='waited too long for "pending", or "initiating" status to go away ({0})'.format(
                    running_status
                ),
                state=state,
            )

        time.sleep(sleep_time)
        running_status = status()


# Traceback (nTypeError)
fatal: [myhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to myhostclosed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 218, in <module>\r\n    main()\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 164, in main\r\n    wait_for_monit_to_stop_pending()\r\n  File \"/tmp/ansible_1cM8fu/ansible_module_monit.py\", line 127, in wait_for_monit_to_stop_pending\r\n    running_status = status()\r\nTypeError: 'str' object is not callable\r\n", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/johan/ansible/only_collectd.retry

# Fixed code
def wait_for_monit_to_stop_pending():
    """Fails this run if there is no status or it's pending/initializing for timeout"""
    timeout_time = time.time() + timeout
    sleep_time = 5

    running_status = get_status()
    while (
        running_status == ""
        or "pending" in running_status
        or "initializing" in running_status
    ):
        if time.time() >= timeout_time:
            module.fail_json(
                msg='waited too long for "pending", or "initiating" status to go away ({0})'.format(
                    running_status
                ),
                state=state,
            )

        time.sleep(sleep_time)
        running_status = get_status()
# Buggy code
def cleanup(self):
    # close active persistent connections
    for sock in itervalues(self._active_connections):
        conn = Connection(sock)
        conn.reset()
    self._final_q.put(_sentinel)
    self._results_thread.join()


# Traceback (ConnectionError)
TASK [Has any previous test failed?] **************************************************************************************************************
task path: /Users/gnalawad/ansible/ganeshrn/ansible/test/integration/junos.yaml:174
skipping: [junos] => {
"changed": false,
"skip_reason": "Conditional result was False"
}
META: ran handlers
META: ran handlers
ERROR! Unexpected Exception, this is probably a bug: socket_path does not exist or cannot be found
the full traceback was:

Traceback (most recent call last):
File "/Users/gnalawad/ansible/ganeshrn/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/executor/playbook_executor.py", line 154, in run
result = self._tqm.run(play=play)
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/executor/task_queue_manager.py", line 296, in run
strategy.cleanup()
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/plugins/strategy/__init__.py", line 146, in cleanup
conn.reset()
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/module_utils/connection.py", line 140, in __rpc__
response = self._exec_jsonrpc(name, *args, **kwargs)
File "/Users/gnalawad/ansible/ganeshrn/ansible/lib/ansible/module_utils/connection.py", line 115, in _exec_jsonrpc
raise ConnectionError('socket_path does not exist or cannot be found')
ConnectionError: socket_path does not exist or cannot be found

# Fixed code
def cleanup(self):
    # close active persistent connections
    for sock in itervalues(self._active_connections):
        try:
            conn = Connection(sock)
            conn.reset()
        except ConnectionError as e:
            # most likely socket is already closed
            display.debug("got an error while closing persistent connection: %s" % e)
    self._final_q.put(_sentinel)
    self._results_thread.join()
# Buggy code
def set_options(self, options):
    super(CallbackModule, self).set_options(options)

    self.sort_order = self._plugin_options["sort_order"]
    if self.sort_order is not None:
        if self.sort_order == "ascending":
            self.sort_order = False
        elif self.sort_order == "descending":
            self.sort_order = True
        elif self.sort_order == "none":
            self.sort_order = None

    self.task_output_limit = self._plugin_options["output_limit"]
    if self.task_output_limit is not None:
        if self.task_output_limit == "all":
            self.task_output_limit = None
        else:
            self.task_output_limit = int(self.task_output_limit)


# Traceback (TypeError)
$ ansible-playbook test_play.yml -vvv
ansible-playbook 2.5.0 (devel a40ce1ba5e) last updated 2017/11/17 16:31:10 (GMT +1000)
config file = /home/will/src/ansible/ansible.cfg
configured module search path = [u'/home/will/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /home/will/src/ansible/lib/ansible
executable location = /home/will/src/ansible/bin/ansible-playbook
python version = 2.7.14 (default, Nov  2 2017, 18:42:05) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)]
Using /home/will/src/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin
[WARNING]: Could not match supplied host pattern, ignoring: all

[WARNING]: provided hosts list is empty, only localhost is available

ERROR! Unexpected Exception, this is probably a bug: set_options() takes exactly 2 arguments (1 given)
the full traceback was:

Traceback (most recent call last):
File "/home/will/src/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/home/will/src/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/will/src/ansible/lib/ansible/executor/playbook_executor.py", line 90, in run
self._tqm.load_callbacks()
File "/home/will/src/ansible/lib/ansible/executor/task_queue_manager.py", line 210, in load_callbacks
callback_obj.set_options()
TypeError: set_options() takes exactly 2 arguments (1 given)

# Fixed code
def set_options(self, task_keys=None, var_options=None, direct=None):
    super(CallbackModule, self).set_options(
        task_keys=task_keys, var_options=var_options, direct=direct
    )

    self.sort_order = self._plugin_options["sort_order"]
    if self.sort_order is not None:
        if self.sort_order == "ascending":
            self.sort_order = False
        elif self.sort_order == "descending":
            self.sort_order = True
        elif self.sort_order == "none":
            self.sort_order = None

    self.task_output_limit = self._plugin_options["output_limit"]
    if self.task_output_limit is not None:
        if self.task_output_limit == "all":
            self.task_output_limit = None
        else:
            self.task_output_limit = int(self.task_output_limit)
# Buggy code
def set_options(self, options):
    super(CallbackModule, self).set_options(options)

    global DONT_COLORIZE
    DONT_COLORIZE = self._plugin_options["nocolor"]


# Traceback (TypeError)
$ ansible-playbook test_play.yml -vvv
ansible-playbook 2.5.0 (devel a40ce1ba5e) last updated 2017/11/17 16:31:10 (GMT +1000)
config file = /home/will/src/ansible/ansible.cfg
configured module search path = [u'/home/will/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /home/will/src/ansible/lib/ansible
executable location = /home/will/src/ansible/bin/ansible-playbook
python version = 2.7.14 (default, Nov  2 2017, 18:42:05) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)]
Using /home/will/src/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin
[WARNING]: Could not match supplied host pattern, ignoring: all

[WARNING]: provided hosts list is empty, only localhost is available

ERROR! Unexpected Exception, this is probably a bug: set_options() takes exactly 2 arguments (1 given)
the full traceback was:

Traceback (most recent call last):
File "/home/will/src/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/home/will/src/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/will/src/ansible/lib/ansible/executor/playbook_executor.py", line 90, in run
self._tqm.load_callbacks()
File "/home/will/src/ansible/lib/ansible/executor/task_queue_manager.py", line 210, in load_callbacks
callback_obj.set_options()
TypeError: set_options() takes exactly 2 arguments (1 given)

# Fixed code
def set_options(self, task_keys=None, var_options=None, direct=None):
    super(CallbackModule, self).set_options(
        task_keys=task_keys, var_options=var_options, direct=direct
    )

    global DONT_COLORIZE
    DONT_COLORIZE = self._plugin_options["nocolor"]
# Buggy code
def set_options(self, options):
    super(CallbackModule, self).set_options(options)

    self.webhook_url = self._plugin_options["webhook_url"]
    self.channel = self._plugin_options["channel"]
    self.username = self._plugin_options["username"]
    self.show_invocation = self._display.verbosity > 1

    if self.webhook_url is None:
        self.disabled = True
        self._display.warning(
            "Slack Webhook URL was not provided. The "
            "Slack Webhook URL can be provided using "
            "the `SLACK_WEBHOOK_URL` environment "
            "variable."
        )


# Traceback (TypeError)
$ ansible-playbook test_play.yml -vvv
ansible-playbook 2.5.0 (devel a40ce1ba5e) last updated 2017/11/17 16:31:10 (GMT +1000)
config file = /home/will/src/ansible/ansible.cfg
configured module search path = [u'/home/will/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /home/will/src/ansible/lib/ansible
executable location = /home/will/src/ansible/bin/ansible-playbook
python version = 2.7.14 (default, Nov  2 2017, 18:42:05) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)]
Using /home/will/src/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin
[WARNING]: Could not match supplied host pattern, ignoring: all

[WARNING]: provided hosts list is empty, only localhost is available

ERROR! Unexpected Exception, this is probably a bug: set_options() takes exactly 2 arguments (1 given)
the full traceback was:

Traceback (most recent call last):
File "/home/will/src/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/home/will/src/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/will/src/ansible/lib/ansible/executor/playbook_executor.py", line 90, in run
self._tqm.load_callbacks()
File "/home/will/src/ansible/lib/ansible/executor/task_queue_manager.py", line 210, in load_callbacks
callback_obj.set_options()
TypeError: set_options() takes exactly 2 arguments (1 given)

# Fixed code
def set_options(self, task_keys=None, var_options=None, direct=None):
    super(CallbackModule, self).set_options(
        task_keys=task_keys, var_options=var_options, direct=direct
    )

    self.webhook_url = self._plugin_options["webhook_url"]
    self.channel = self._plugin_options["channel"]
    self.username = self._plugin_options["username"]
    self.show_invocation = self._display.verbosity > 1

    if self.webhook_url is None:
        self.disabled = True
        self._display.warning(
            "Slack Webhook URL was not provided. The "
            "Slack Webhook URL can be provided using "
            "the `SLACK_WEBHOOK_URL` environment "
            "variable."
        )
# Buggy code
def user_add(cursor, user, password, role_attr_flags, encrypted, expires):
    """Create a new database user (role)."""
    # Note: role_attr_flags escaped by parse_role_attrs and encrypted is a literal
    query_password_data = dict(password=password, expires=expires)
    query = ["CREATE USER %(user)s" % {"user": pg_quote_identifier(user, "role")}]
    if password is not None:
        query.append("WITH %(crypt)s" % {"crypt": encrypted})
        query.append("PASSWORD %(password)s")
    if expires is not None:
        query.append("VALID UNTIL %(expires)s")
    query.append(role_attr_flags)
    query = " ".join(query)
    cursor.execute(query, query_password_data)
    return True


# Traceback (psycopg2.ProgrammingError)
failed: [...] => {"failed": true, "parsed": false}
invalid output was: SUDO-SUCCESS-qwpjepgvenunnlewzwjddpnrbfjyptxo
Traceback (most recent call last):
File "/home/ubuntu/.ansible/tmp/ansible-tmp-1407775799.05-32923950289495/postgresql_user", line 1869, in <module>
main()
File "/home/ubuntu/.ansible/tmp/ansible-tmp-1407775799.05-32923950289495/postgresql_user", line 497, in main
changed = user_alter(cursor, module, user, password, role_attr_flags, encrypted, expires)
File "/home/ubuntu/.ansible/tmp/ansible-tmp-1407775799.05-32923950289495/postgresql_user", line 201, in user_alter
cursor.execute(select, {"user": user})
psycopg2.ProgrammingError: permission denied for relation pg_authid

# Fixed code
def user_add(cursor, user, password, role_attr_flags, encrypted, expires):
    """Create a new database user (role)."""
    # Note: role_attr_flags escaped by parse_role_attrs and encrypted is a
    # literal
    query_password_data = dict(password=password, expires=expires)
    query = ["CREATE USER %(user)s" % {"user": pg_quote_identifier(user, "role")}]
    if password is not None:
        query.append("WITH %(crypt)s" % {"crypt": encrypted})
        query.append("PASSWORD %(password)s")
    if expires is not None:
        query.append("VALID UNTIL %(expires)s")
    query.append(role_attr_flags)
    query = " ".join(query)
    cursor.execute(query, query_password_data)
    return True
# Buggy code
def list_modules(self):
    modules = set()
    if self.options.module_path is not None:
        for i in self.options.module_path.split(os.pathsep):
            module_loader.add_directory(i)

    module_paths = module_loader._get_paths()
    for path in module_paths:
        if path is not None:
            modules.update(self._find_modules_in_path(path))
    return modules


# Traceback (AttributeError)
ERROR! Unexpected Exception, this is probably a bug: 'list' object has no attribute 'split'
the full traceback was:

Traceback (most recent call last):
File "/home/user/ansible/ansible/bin/ansible-doc", line 109, in <module>
exit_code = cli.run()
File "/home/user/ansible/ansible/lib/ansible/cli/doc.py", line 107, in run
for i in self.options.module_path.split(os.pathsep):
AttributeError: 'list' object has no attribute 'split'

# Fixed code
def list_modules(self):
    modules = set()
    if self.options.module_path:
        for path in self.options.module_path:
            if path:
                module_loader.add_directory(path)

    module_paths = module_loader._get_paths()
    for path in module_paths:
        if path is not None:
            modules.update(self._find_modules_in_path(path))
    return modules
# Buggy code
def parse_ipv6_interfaces(self, data):
    data = data["TABLE_intf"]
    if isinstance(data, dict):
        data = [data]
    for item in data:
        name = item["ROW_intf"]["intf-name"]
        intf = self.facts["interfaces"][name]
        intf["ipv6"] = self.transform_dict(item, self.INTERFACE_IPV6_MAP)
        self.facts["all_ipv6_addresses"].append(item["ROW_intf"]["addr"])


# Traceback (TypeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: string indices must be integers, not str
fatal: [N9396-Leaf1]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_Lull7D/ansible_module_nxos_facts.py\", line 530, in <module>\n    main()\n  File \"/tmp/ansible_Lull7D/ansible_module_nxos_facts.py\", line 513, in main\n    inst.populate()\n  File \"/tmp/ansible_Lull7D/ansible_module_nxos_facts.py\", line 294, in populate\n    self.parse_ipv6_interfaces(data)\n  File \"/tmp/ansible_Lull7D/ansible_module_nxos_facts.py\", line 352, in parse_ipv6_interfaces\n    data = data['TABLE_intf']\nTypeError: string indices must be integers, not str\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/ansible/playbook.retry

# Fixed code
def parse_ipv6_interfaces(self, data):
    try:
        data = data["TABLE_intf"]
        if data:
            if isinstance(data, dict):
                data = [data]
            for item in data:
                name = item["ROW_intf"]["intf-name"]
                intf = self.facts["interfaces"][name]
                intf["ipv6"] = self.transform_dict(item, self.INTERFACE_IPV6_MAP)
                self.facts["all_ipv6_addresses"].append(item["ROW_intf"]["addr"])
        else:
            return ""
    except TypeError:
        return ""
# Buggy code
def main():
    (parser, config_path) = C.load_config_file()
    if parser.has_option("vault", "username"):
        username = parser.get("vault", "username")
    else:
        username = getpass.getuser()

    if parser.has_option("vault", "keyname"):
        keyname = parser.get("vault", "keyname")
    else:
        keyname = "ansible"

    if len(sys.argv) == 2 and sys.argv[1] == "set":
        intro = 'Storing password in "{}" user keyring using key name: {}\n'
        sys.stdout.write(intro.format(username, keyname))
        password = getpass.getpass()
        confirm = getpass.getpass("Confirm password: ")
        if password == confirm:
            keyring.set_password(keyname, username, password)
        else:
            sys.stderr.write("Passwords do not match\n")
            sys.exit(1)
    else:
        sys.stdout.write("{}\n".format(keyring.get_password(keyname, username)))

    sys.exit(0)


# Traceback (AttributeError)
$ ./contrib/vault/vault-keyring.py
Traceback (most recent call last):
File "./contrib/vault/vault-keyring.py", line 101, in <module>
main()
File "./contrib/vault/vault-keyring.py", line 72, in main
(parser, config_path) = C.load_config_file()
AttributeError: 'module' object has no attribute 'load_config_file'

# Fixed code
def main():
    config = ConfigManager()
    username = (
        get_ini_config_value(config._parser, dict(section="vault", key="username"))
        or getpass.getuser()
    )

    keyname = (
        get_ini_config_value(config._parser, dict(section="vault", key="keyname"))
        or "ansible"
    )

    if len(sys.argv) == 2 and sys.argv[1] == "set":
        intro = 'Storing password in "{}" user keyring using key name: {}\n'
        sys.stdout.write(intro.format(username, keyname))
        password = getpass.getpass()
        confirm = getpass.getpass("Confirm password: ")
        if password == confirm:
            keyring.set_password(keyname, username, password)
        else:
            sys.stderr.write("Passwords do not match\n")
            sys.exit(1)
    else:
        sys.stdout.write("{}\n".format(keyring.get_password(keyname, username)))

    sys.exit(0)
# Buggy code
def add_rules_to_lookup(ipPermissions, group_id, prefix, dict):
    for rule in ipPermissions:
        for groupGrant in rule.get("UserIdGroupPairs"):
            dict[make_rule_key(prefix, rule, group_id, groupGrant.get("GroupId"))] = (
                rule,
                groupGrant,
            )
        for ipv4Grants in rule.get("IpRanges"):
            dict[make_rule_key(prefix, rule, group_id, ipv4Grants.get("CidrIp"))] = (
                rule,
                ipv4Grants,
            )
        for ipv6Grants in rule.get("Ipv6Ranges"):
            dict[make_rule_key(prefix, rule, group_id, ipv6Grants.get("CidrIpv6"))] = (
                rule,
                ipv6Grants,
            )


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_pIaxjv/ansible_module_ec2_group.py", line 899, in <module>
main()
File "/tmp/ansible_pIaxjv/ansible_module_ec2_group.py", line 801, in main
add_rules_to_lookup(group['IpPermissionsEgress'], group['GroupId'], 'out', groupRules)
File "/tmp/ansible_pIaxjv/ansible_module_ec2_group.py", line 314, in add_rules_to_lookup
for ipv6Grants in rule.get('Ipv6Ranges'):
TypeError: 'NoneType' object is not iterable

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_pIaxjv/ansible_module_ec2_group.py\", line 899, in <module>\n    main()\n  File \"/tmp/ansible_pIaxjv/ansible_module_ec2_group.py\", line 801, in main\n    add_rules_to_lookup(group['IpPermissionsEgress'], group['GroupId'], 'out', groupRules)\n  File \"/tmp/ansible_pIaxjv/ansible_module_ec2_group.py\", line 314, in add_rules_to_lookup\n    for ipv6Grants in rule.get('Ipv6Ranges'):\nTypeError: 'NoneType' object is not iterable\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def add_rules_to_lookup(ipPermissions, group_id, prefix, dict):
    for rule in ipPermissions:
        for groupGrant in rule.get("UserIdGroupPairs", []):
            dict[make_rule_key(prefix, rule, group_id, groupGrant.get("GroupId"))] = (
                rule,
                groupGrant,
            )
        for ipv4Grants in rule.get("IpRanges", []):
            dict[make_rule_key(prefix, rule, group_id, ipv4Grants.get("CidrIp"))] = (
                rule,
                ipv4Grants,
            )
        for ipv6Grants in rule.get("Ipv6Ranges", []):
            dict[make_rule_key(prefix, rule, group_id, ipv6Grants.get("CidrIpv6"))] = (
                rule,
                ipv6Grants,
            )
# Buggy code
def get_vars_files(self):
    return self.vars_files


# Traceback (TypeError)
ubuntu@ubuntu-xenial:~/ansible/playbooks$ ansible-playbook ./debug_vars_files.yml -vvv
ansible-playbook 2.5.0 (devel 101377768b) last updated 2017/10/03 14:54:07 (GMT +000)
config file = /sbux_ansible/ansible.cfg
configured module search path = [u'/sbux_ansible/library', u'/usr/share/ansible']
ansible python module location = /home/ubuntu/ansible/lib/ansible
executable location = /home/ubuntu/ansible/bin/ansible-playbook
python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]
Using /sbux_ansible/ansible.cfg as config file
Parsed /sbux_ansible/inventory.txt inventory source with ini plugin

PLAYBOOK: debug_vars_files.yml *****************************************************************************************************
1 plays in ./debug_vars_files.yml
ERROR! Unexpected Exception, this is probably a bug: 'NoneType' object is not iterable
the full traceback was:

Traceback (most recent call last):
File "/home/ubuntu/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/home/ubuntu/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/ubuntu/ansible/lib/ansible/executor/playbook_executor.py", line 126, in run
all_vars = self._variable_manager.get_vars(play=play)
File "/home/ubuntu/ansible/lib/ansible/vars/manager.py", line 348, in get_vars
for vars_file_item in play.get_vars_files():
TypeError: 'NoneType' object is not iterable

# Fixed code
def get_vars_files(self):
    if self.vars_files is None:
        return []
    return self.vars_files
# Buggy code
def delete(self, key):
    del self.cache[key]
    self._db.delete(self._make_key(key))
    self._db.zrem(self._keys_set, key)


# Traceback (AttributeError)
root@ansible:/etc/ansible# ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook -i environments/cadastre-am/ cadastre-am.yml --flush-cache --diff -vvv
ansible-playbook 2.4.0.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.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-playbook
python version = 2.7.9 (default, Jun 29 2016, 13:08:31) [GCC 4.9.2]
Using /etc/ansible/ansible.cfg as config file
Parsed /etc/ansible/environments/cadastre-am/hosts inventory source with ini plugin
ERROR! Unexpected Exception, this is probably a bug: 'CacheModule' object has no attribute 'cache'
the full traceback was:

Traceback (most recent call last):
File "/usr/bin/ansible-playbook", line 106, in <module>
exit_code = cli.run()
File "/usr/lib/python2.7/dist-packages/ansible/cli/playbook.py", line 124, in run
self._flush_cache(inventory, variable_manager)
File "/usr/lib/python2.7/dist-packages/ansible/cli/playbook.py", line 204, in _flush_cache
variable_manager.clear_facts(hostname)
File "/usr/lib/python2.7/dist-packages/ansible/vars/manager.py", line 590, in clear_facts
del self._fact_cache[hostname]
File "/usr/lib/python2.7/dist-packages/ansible/plugins/cache/__init__.py", line 260, in __delitem__
self._plugin.delete(key)
File "/usr/lib/python2.7/dist-packages/ansible/plugins/cache/redis.py", line 119, in delete
del self.cache[key]
AttributeError: 'CacheModule' object has no attribute 'cache'

# Fixed code
def delete(self, key):
    del self._cache[key]
    self._db.delete(self._make_key(key))
    self._db.zrem(self._keys_set, key)