gurudesh/pytracebugs huggingface dataset:
# Buggy code
def on_become(self, passwd=None):
    if self._get_prompt().endswith(b"#"):
        return

    cmd = {"command": "enable"}
    if passwd:
        # Note: python-3.5 cannot combine u"" and r"" together.  Thus make
        # an r string and use to_text to ensure it's text on both py2 and py3.
        cmd["prompt"] = to_text(r"[\r\n]password: ?$", errors="surrogate_or_strict")
        cmd["answer"] = passwd
        cmd["prompt_retry_check"] = True
    try:
        self._exec_cli_command(to_bytes(json.dumps(cmd), errors="surrogate_or_strict"))
        prompt = self._get_prompt()
        if prompt is None or not prompt.endswith(b"#"):
            raise AnsibleConnectionFailure(
                "failed to elevate privilege to enable mode still at prompt [%s]"
                % prompt
            )
    except AnsibleConnectionFailure as e:
        prompt = self._get_prompt()
        raise AnsibleConnectionFailure(
            "unable to elevate privilege to enable mode, at prompt [%s] with error: %s"
            % (prompt, e.message)
        )


# Traceback (nIndexError)
FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/dq/_tjy3jfn0j98n6j590nyr24jpxb_7r/T/ansible_ad9N9O/ansible_module_ios_facts.py\", line 518, in <module>\n    main()\n  File \"/var/folders/dq/_tjy3jfn0j98n6j590nyr24jpxb_7r/T/ansible_ad9N9O/ansible_module_ios_facts.py\", line 503, in main\n    inst.populate()\n  File \"/var/folders/dq/_tjy3jfn0j98n6j590nyr24jpxb_7r/T/ansible_ad9N9O/ansible_module_ios_facts.py\", line 232, in populate\n    if 'Processor' in l].pop()\nIndexError: pop from empty list\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def on_become(self, passwd=None):
    if self._get_prompt().endswith(b"#"):
        return

    cmd = {"command": "enable"}
    if passwd:
        # Note: python-3.5 cannot combine u"" and r"" together.  Thus make
        # an r string and use to_text to ensure it's text on both py2 and py3.
        cmd["prompt"] = to_text(
            r"[\r\n](?:Local_)?[Pp]assword: ?$", errors="surrogate_or_strict"
        )
        cmd["answer"] = passwd
        cmd["prompt_retry_check"] = True
    try:
        self._exec_cli_command(to_bytes(json.dumps(cmd), errors="surrogate_or_strict"))
        prompt = self._get_prompt()
        if prompt is None or not prompt.endswith(b"#"):
            raise AnsibleConnectionFailure(
                "failed to elevate privilege to enable mode still at prompt [%s]"
                % prompt
            )
    except AnsibleConnectionFailure as e:
        prompt = self._get_prompt()
        raise AnsibleConnectionFailure(
            "unable to elevate privilege to enable mode, at prompt [%s] with error: %s"
            % (prompt, e.message)
        )
# Buggy code
def get_config_value(
    self,
    config,
    cfile=None,
    plugin_type=None,
    plugin_name=None,
    keys=None,
    variables=None,
):
    """wrapper"""
    value, _drop = self.get_config_value_and_origin(
        config,
        cfile=cfile,
        plugin_type=plugin_type,
        plugin_name=plugin_name,
        keys=keys,
        variables=variables,
    )
    return value


# Traceback (OptionValueError)
[fedora-25:ansible (devel % u=)]$ ANSIBLE_TIMEOUT= ansible -vvv localhost -m ping
ERROR! Unexpected Exception: option --timeout: invalid integer value: u''
the full traceback was:

Traceback (most recent call last):
File "/home/adrian/src/ansible/bin/ansible", line 102, in <module>
cli.parse()
File "/home/adrian/src/ansible/lib/ansible/cli/adhoc.py", line 75, in parse
super(AdHocCLI, self).parse()
File "/home/adrian/src/ansible/lib/ansible/cli/__init__.py", line 438, in parse
self.options, self.args = self.parser.parse_args(self.args[1:])
File "/usr/lib64/python2.7/optparse.py", line 1384, in parse_args
values = self.get_default_values()
File "/usr/lib64/python2.7/optparse.py", line 1329, in get_default_values
defaults[option.dest] = option.check_value(opt_str, default)
File "/usr/lib64/python2.7/optparse.py", line 770, in check_value
return checker(self, opt, value)
File "/usr/lib64/python2.7/optparse.py", line 430, in check_builtin
_("option %s: invalid %s value: %r") % (opt, what, value))
OptionValueError: option --timeout: invalid integer value: u''

# Fixed code
def get_config_value(
    self,
    config,
    cfile=None,
    plugin_type=None,
    plugin_name=None,
    keys=None,
    variables=None,
):
    """wrapper"""

    try:
        value, _drop = self.get_config_value_and_origin(
            config,
            cfile=cfile,
            plugin_type=plugin_type,
            plugin_name=plugin_name,
            keys=keys,
            variables=variables,
        )
    except Exception as e:
        raise AnsibleError(
            "Invalid settings supplied for %s: %s" % (config, to_native(e))
        )
    return value
# Buggy code
def create_vgw(client, module):
    params = dict()
    params["Type"] = module.params.get("type")

    try:
        response = client.create_vpn_gateway(Type=params["Type"])
        get_waiter(client, "vpn_gateway_exists").wait(
            VpnGatewayIds=[response["VpnGateway"]["VpnGatewayId"]]
        )
    except botocore.exceptions.WaiterError as e:
        module.fail_json(
            msg="Failed to wait for Vpn Gateway {0} to be available".format(
                response["VpnGateway"]["VpnGatewayId"]
            ),
            exception=traceback.format_exc(),
        )
    except botocore.exceptions.ClientError as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    result = response
    return result


# Traceback (botocore.exceptions.ClientError)
Traceback (most recent call last):
File "/tmp/ansible_bnu8ct97/ansible_module_ec2_vpc_vgw.py", line 208, in create_vgw
response = client.create_vpn_gateway(Type=params['Type'])
File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python3.6/dist-packages/botocore/client.py", line 612, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (VpnGatewayLimitExceeded) when calling the CreateVpnGateway operation: The maximum number of virtual private gateways has been reached.

# Fixed code
def create_vgw(client, module):
    params = dict()
    params["Type"] = module.params.get("type")

    try:
        response = client.create_vpn_gateway(Type=params["Type"])
        get_waiter(client, "vpn_gateway_exists").wait(
            VpnGatewayIds=[response["VpnGateway"]["VpnGatewayId"]]
        )
    except botocore.exceptions.WaiterError as e:
        module.fail_json(
            msg="Failed to wait for Vpn Gateway {0} to be available".format(
                response["VpnGateway"]["VpnGatewayId"]
            ),
            exception=traceback.format_exc(),
        )
    except client.exceptions.from_code("VpnGatewayLimitExceeded") as e:
        module.fail_json(
            msg="Too many VPN gateways exist in this account.",
            exception=traceback.format_exc(),
        )
    except botocore.exceptions.ClientError as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    result = response
    return result
# Buggy code
def parse_interfaces(module, vlan):
    vlan_int = []
    interfaces = vlan.get("vlanshowplist-ifidx")
    if interfaces:
        for i in interfaces.split(","):
            if "eth" in i.lower() and "-" in i:
                int_range = i.split("-")
                stop = int((int_range)[1])
                start = int(int_range[0].split("/")[1])
                eth = int_range[0].split("/")[0]
                for r in range(start, stop + 1):
                    vlan_int.append(eth + "/" + str(r))
            else:
                vlan_int.append(i)

    return vlan_int


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py", line 602, in <module>
main()
File "/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py", line 580, in main
have = map_config_to_obj(module, os_platform)
File "/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py", line 499, in map_config_to_obj
obj = parse_vlan_options(module, os_platform, output, vlan)
File "/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py", line 484, in parse_vlan_options
obj['interfaces'] = parse_interfaces(module, vlan)
File "/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py", line 461, in parse_interfaces
for i in interfaces.split(','):
AttributeError: 'list' object has no attribute 'split'

fatal: [192.168.141.162]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py\", line 602, in <module>\n    main()\n  File \"/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py\", line 580, in main\n    have = map_config_to_obj(module, os_platform)\n  File \"/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py\", line 499, in map_config_to_obj\n    obj = parse_vlan_options(module, os_platform, output, vlan)\n  File \"/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py\", line 484, in parse_vlan_options\n    obj['interfaces'] = parse_interfaces(module, vlan)\n  File \"/tmp/ansible_hyyN69/ansible_module_nxos_vlan.py\", line 461, in parse_interfaces\n    for i in interfaces.split(','):\nAttributeError: 'list' object has no attribute 'split'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def parse_interfaces(module, vlan):
    vlan_int = []
    interfaces = vlan.get("vlanshowplist-ifidx")
    if interfaces:
        if isinstance(interfaces, list):
            interfaces_list = [i.strip() for i in interfaces]
            interfaces_str = ",".join(interfaces_list)
            vlan_int = get_vlan_int(interfaces_str)
        else:
            vlan_int = get_vlan_int(interfaces)
    return vlan_int
# Buggy code
def user_password(self):
    passwd = ""
    expires = ""
    if HAVE_SPWD:
        try:
            passwd = spwd.getspnam(self.name)[1]
            expires = spwd.getspnam(self.name)[7]
            return passwd, expires
        except KeyError:
            return passwd, expires

    if not self.user_exists():
        return passwd, expires
    elif self.SHADOWFILE:
        # Read shadow file for user's encrypted password string
        if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK):
            for line in open(self.SHADOWFILE).readlines():
                if line.startswith("%s:" % self.name):
                    passwd = line.split(":")[1]
                    expires = line.split(":")[self.SHADOWFILE_EXPIRE_INDEX] or -1
    return passwd, expires


# Traceback (nPermissionError)
fatal: [myhost]: FAILED! => {
"changed": false,
"module_stderr": "Shared connection to localhost closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 2255, in <module>\r\n    main()\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 2193, in main\r\n    (rc, out, err) = user.modify_user()\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 698, in modify_user\r\n    return self.modify_user_usermod()\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 455, in modify_user_usermod\r\n    info = self.user_info()\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 599, in user_info\r\n    info[1] = self.user_password()\r\n  File \"/tmp/ansible_xydrgos5/ansible_module_user.py\", line 606, in user_password\r\n    passwd = spwd.getspnam(self.name)[1]\r\nPermissionError: [Errno 13] Permission denied\r\n",
"msg": "MODULE FAILURE",
"rc": 1

# Fixed code
def user_password(self):
    passwd = ""
    expires = ""
    if HAVE_SPWD:
        try:
            passwd = spwd.getspnam(self.name)[1]
            expires = spwd.getspnam(self.name)[7]
            return passwd, expires
        except KeyError:
            return passwd, expires
        except OSError as e:
            # Python 3.6 raises PermissionError instead of KeyError
            # Due to absence of PermissionError in python2.7 need to check
            # errno
            if e.errno in (errno.EACCES, errno.EPERM):
                return passwd, expires
            raise

    if not self.user_exists():
        return passwd, expires
    elif self.SHADOWFILE:
        # Read shadow file for user's encrypted password string
        if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK):
            for line in open(self.SHADOWFILE).readlines():
                if line.startswith("%s:" % self.name):
                    passwd = line.split(":")[1]
                    expires = line.split(":")[self.SHADOWFILE_EXPIRE_INDEX] or -1
    return passwd, expires
# Buggy code
def get_device_info(self):
    device_info = {}

    device_info["network_os"] = "ios"
    reply = self.get("show version")
    data = to_text(reply, errors="surrogate_or_strict").strip()

    match = re.search(r"Version (\S+),", data)
    if match:
        device_info["network_os_version"] = match.group(1)

    match = re.search(r"^Cisco (.+) \(revision", data, re.M)
    if match:
        device_info["network_os_model"] = match.group(1)

    match = re.search(r"^(.+) uptime", data, re.M)
    if match:
        device_info["network_os_hostname"] = match.group(1)

    return device_info


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_l_K2xc/ansible_module_ios_logging.py", line 416, in <module>
main()
File "/tmp/ansible_l_K2xc/ansible_module_ios_logging.py", line 393, in main
os_version = device_info['device_info']['network_os_version']
KeyError: 'network_os_version'

fatal: [lab2_user1]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_l_K2xc/ansible_module_ios_logging.py\", line 416, in <module>\n    main()\n  File \"/tmp/ansible_l_K2xc/ansible_module_ios_logging.py\", line 393, in main\n    os_version = device_info['device_info']['network_os_version']\nKeyError: 'network_os_version'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def get_device_info(self):
    device_info = {}

    device_info["network_os"] = "ios"
    reply = self.get("show version")
    data = to_text(reply, errors="surrogate_or_strict").strip()

    match = re.search(r"Version (\S+)", data)
    if match:
        device_info["network_os_version"] = match.group(1).strip(",")

    match = re.search(r"^Cisco (.+) \(revision", data, re.M)
    if match:
        device_info["network_os_model"] = match.group(1)

    match = re.search(r"^(.+) uptime", data, re.M)
    if match:
        device_info["network_os_hostname"] = match.group(1)

    return device_info
# Buggy code
def ensure_tags(module, vpc_conn, resource_id, tags, add_only, check_mode):
    try:
        cur_tags = get_resource_tags(vpc_conn, resource_id)
        if tags == cur_tags:
            return {"changed": False, "tags": cur_tags}

        to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
        if to_delete and not add_only:
            vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)

        to_add = dict((k, tags[k]) for k in tags if k not in cur_tags)
        if to_add:
            vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)

        latest_tags = get_resource_tags(vpc_conn, resource_id)
        return {"changed": True, "tags": latest_tags}
    except EC2ResponseError as e:
        module.fail_json(
            msg="Failed to modify tags: %s" % e.message,
            exception=traceback.format_exc(),
        )


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def ensure_tags(module, vpc_conn, resource_id, tags, add_only, check_mode):
    try:
        cur_tags = get_resource_tags(vpc_conn, resource_id)
        if tags == cur_tags:
            return {"changed": False, "tags": cur_tags}

        to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
        if to_delete and not add_only:
            retry_not_found(
                vpc_conn.delete_tags, resource_id, to_delete, dry_run=check_mode
            )

        to_add = dict((k, tags[k]) for k in tags if k not in cur_tags)
        if to_add:
            retry_not_found(
                vpc_conn.create_tags, resource_id, to_add, dry_run=check_mode
            )

        latest_tags = get_resource_tags(vpc_conn, resource_id)
        return {"changed": True, "tags": latest_tags}
    except EC2ResponseError as e:
        module.fail_json(
            msg="Failed to modify tags: %s" % e.message,
            exception=traceback.format_exc(),
        )
# Buggy code
def get_vpc(module, connection, vpc_id):
    try:
        vpc_obj = connection.describe_vpcs(VpcIds=[vpc_id])["Vpcs"][0]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")
    try:
        classic_link = connection.describe_vpc_classic_link(VpcIds=[vpc_id])["Vpcs"][
            0
        ].get("ClassicLinkEnabled")
        vpc_obj["ClassicLinkEnabled"] = classic_link
    except botocore.exceptions.ClientError as e:
        if (
            e.response["Error"]["Message"]
            == "The functionality you requested is not available in this region."
        ):
            vpc_obj["ClassicLinkEnabled"] = False
        else:
            module.fail_json_aws(e, msg="Failed to describe VPCs")
    except botocore.exceptions.BotoCoreError as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    return vpc_obj


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def get_vpc(module, connection, vpc_id):
    # wait for vpc to be available
    try:
        connection.get_waiter("vpc_available").wait(VpcIds=[vpc_id])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(
            e, msg="Unable to wait for VPC {0} to be available.".format(vpc_id)
        )

    try:
        vpc_obj = AWSRetry.backoff(
            delay=3,
            tries=8,
            catch_extra_error_codes=["InvalidVpcID.NotFound"],
        )(connection.describe_vpcs)(VpcIds=[vpc_id])["Vpcs"][0]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")
    try:
        vpc_obj["ClassicLinkEnabled"] = get_classic_link_with_backoff(
            connection, vpc_id
        )
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    return vpc_obj
# Buggy code
def update_vpc_tags(connection, module, vpc_id, tags, name):
    if tags is None:
        tags = dict()

    tags.update({"Name": name})
    try:
        current_tags = dict(
            (t["Key"], t["Value"])
            for t in connection.describe_tags(
                Filters=[{"Name": "resource-id", "Values": [vpc_id]}]
            )["Tags"]
        )
        if tags != current_tags:
            if not module.check_mode:
                tags = ansible_dict_to_boto3_tag_list(tags)
                connection.create_tags(Resources=[vpc_id], Tags=tags)
            return True
        else:
            return False
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to update tags")


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def update_vpc_tags(connection, module, vpc_id, tags, name):
    if tags is None:
        tags = dict()

    tags.update({"Name": name})
    try:
        current_tags = dict(
            (t["Key"], t["Value"])
            for t in connection.describe_tags(
                Filters=[{"Name": "resource-id", "Values": [vpc_id]}]
            )["Tags"]
        )
        if tags != current_tags:
            if not module.check_mode:
                tags = ansible_dict_to_boto3_tag_list(tags)
                vpc_obj = AWSRetry.backoff(
                    delay=1,
                    tries=5,
                    catch_extra_error_codes=["InvalidVpcID.NotFound"],
                )(connection.create_tags)(Resources=[vpc_id], Tags=tags)

                # Wait for tags to be updated
                expected_tags = boto3_tag_list_to_ansible_dict(tags)
                filters = [
                    {"Name": "tag:{0}".format(key), "Values": [value]}
                    for key, value in expected_tags.items()
                ]
                connection.get_waiter("vpc_available").wait(
                    VpcIds=[vpc_id], Filters=filters
                )

            return True
        else:
            return False
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to update tags")
# Buggy code
def update_dhcp_opts(connection, module, vpc_obj, dhcp_id):
    if vpc_obj["DhcpOptionsId"] != dhcp_id:
        if not module.check_mode:
            try:
                connection.associate_dhcp_options(
                    DhcpOptionsId=dhcp_id, VpcId=vpc_obj["VpcId"]
                )
            except (
                botocore.exceptions.ClientError,
                botocore.exceptions.BotoCoreError,
            ) as e:
                module.fail_json_aws(
                    e, msg="Failed to associate DhcpOptionsId {0}".format(dhcp_id)
                )
        return True
    else:
        return False


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def update_dhcp_opts(connection, module, vpc_obj, dhcp_id):
    if vpc_obj["DhcpOptionsId"] != dhcp_id:
        if not module.check_mode:
            try:
                connection.associate_dhcp_options(
                    DhcpOptionsId=dhcp_id, VpcId=vpc_obj["VpcId"]
                )
            except (
                botocore.exceptions.ClientError,
                botocore.exceptions.BotoCoreError,
            ) as e:
                module.fail_json_aws(
                    e, msg="Failed to associate DhcpOptionsId {0}".format(dhcp_id)
                )

            try:
                # Wait for DhcpOptionsId to be updated
                filters = [{"Name": "dhcp-options-id", "Values": [dhcp_id]}]
                connection.get_waiter("vpc_available").wait(
                    VpcIds=[vpc_obj["VpcId"]], Filters=filters
                )
            except (
                botocore.exceptions.ClientError,
                botocore.exceptions.BotoCoreError,
            ) as e:
                module.fail_json(msg="Failed to wait for DhcpOptionsId to be updated")

        return True
    else:
        return False
# Buggy code
def create_vpc(connection, module, cidr_block, tenancy):
    try:
        if not module.check_mode:
            vpc_obj = connection.create_vpc(
                CidrBlock=cidr_block, InstanceTenancy=tenancy
            )
        else:
            module.exit_json(changed=True)
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, "Failed to create the VPC")
    return vpc_obj["Vpc"]["VpcId"]


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def create_vpc(connection, module, cidr_block, tenancy):
    try:
        if not module.check_mode:
            vpc_obj = connection.create_vpc(
                CidrBlock=cidr_block, InstanceTenancy=tenancy
            )
        else:
            module.exit_json(changed=True)
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, "Failed to create the VPC")

    # wait for vpc to exist
    try:
        connection.get_waiter("vpc_exists").wait(VpcIds=[vpc_obj["Vpc"]["VpcId"]])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(
            e,
            msg="Unable to wait for VPC {0} to be created.".format(
                vpc_obj["Vpc"]["VpcId"]
            ),
        )

    return vpc_obj["Vpc"]["VpcId"]
# Buggy code
def get_vpc(module, connection, vpc_id):
    try:
        vpc_obj = AWSRetry.backoff(
            delay=1,
            tries=5,
            catch_extra_error_codes=["InvalidVpcID.NotFound"],
        )(connection.describe_vpcs)(VpcIds=[vpc_id])["Vpcs"][0]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")
    try:
        classic_link = connection.describe_vpc_classic_link(VpcIds=[vpc_id])["Vpcs"][
            0
        ].get("ClassicLinkEnabled")
        vpc_obj["ClassicLinkEnabled"] = classic_link
    except botocore.exceptions.ClientError as e:
        if (
            e.response["Error"]["Message"]
            == "The functionality you requested is not available in this region."
        ):
            vpc_obj["ClassicLinkEnabled"] = False
        else:
            module.fail_json_aws(e, msg="Failed to describe VPCs")
    except botocore.exceptions.BotoCoreError as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    return vpc_obj


# Traceback (boto.exception.EC2ResponseError)
Traceback (most recent call last):
File "/tmp/ansible_oqa3j78q/ansible_module_ec2_vpc_dhcp_option.py", line 233, in ensure_tags
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
File "/usr/local/lib/python3.6/dist-packages/boto/ec2/connection.py", line 4219, in create_tags
return self.get_status('CreateTags', params, verb='POST')
File "/usr/local/lib/python3.6/dist-packages/boto/connection.py", line 1227, in get_status
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidDhcpOptionsID.NotFound</Code><Message>The dhcpOptions ID 'dopt-6cf05914' does not exist</Message></Error></Errors><RequestID>d602f51a-66b5-445f-9b5b-38ffdbccda29</RequestID></Response>

# Fixed code
def get_vpc(module, connection, vpc_id):
    # wait for vpc to be available
    try:
        connection.get_waiter("vpc_available").wait(VpcIds=[vpc_id])
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(
            e, msg="Unable to wait for VPC {0} to be available.".format(vpc_id)
        )

    try:
        vpc_obj = AWSRetry.backoff(
            delay=3,
            tries=8,
            catch_extra_error_codes=["InvalidVpcID.NotFound"],
        )(connection.describe_vpcs)(VpcIds=[vpc_id])["Vpcs"][0]
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")
    try:
        vpc_obj["ClassicLinkEnabled"] = get_classic_link_with_backoff(
            connection, vpc_id
        )
    except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
        module.fail_json_aws(e, msg="Failed to describe VPCs")

    return vpc_obj
# Buggy code
def _fetch(self, url):
    (response, info) = fetch_url(self.module, url, force=True)
    if response:
        data = response.read()
    else:
        data = None
    return to_text(data)


# Traceback (KeyError)
Traceback (most recent call last):
File \"\/tmp\/ansible_hnBbkT\/ansible_module_ec2_metadata_facts.py\", line 548, in <module>
main()
File \"\/tmp\/ansible_hnBbkT\/ansible_module_ec2_metadata_facts.py\", line 541, in main
ec2_metadata_facts = Ec2Metadata(module).run()
File \"\/tmp\/ansible_hnBbkT\/ansible_module_ec2_metadata_facts.py\", line 526, in run
data['ansible_ec2_placement_region'] = data['ansible_ec2_instance_identity_document_region']
KeyError: 'ansible_ec2_instance_identity_document_region'

# Fixed code
def _fetch(self, url):
    response, info = fetch_url(self.module, url, force=True)

    if info.get("status") not in (200, 404):
        time.sleep(3)
        # request went bad, retry once then raise
        self.module.warn(
            "Retrying query to metadata service. First attempt failed: {0}".format(
                info["msg"]
            )
        )
        response, info = fetch_url(self.module, url, force=True)
        if info.get("status") not in (200, 404):
            # fail out now
            self.module.fail_json(
                msg="Failed to retrieve metadata from AWS: {0}".format(info["msg"]),
                response=info,
            )
    if response:
        data = response.read()
    else:
        data = None
    return to_text(data)
# Buggy code
def connect_to_influxdb(self):
    return InfluxDBClient(
        host=self.hostname,
        port=self.port,
        username=self.username,
        password=self.password,
        database=self.database_name,
        ssl=self.params["ssl"],
        verify_ssl=self.params["validate_certs"],
        timeout=self.params["timeout"],
        retries=self.params["retries"],
        use_udp=self.params["use_udp"],
        udp_port=self.params["udp_port"],
        proxies=self.params["proxies"],
    )


# Traceback (nTypeError)
fatal: [phi-monitoring]: FAILED! => {
"changed": false,
"module_stderr": "Shared connection to phi-monitoring closed.\r\n",
"module_stdout": "\r\n\r\nTraceback (most recent call last):\r\n  File \"/tmp/ansible_KfqOgv/ansible_module_influxdb_database.py\", line 143, in <module>\r\n    main()\r\n  File \"/tmp/ansible_KfqOgv/ansible_module_influxdb_database.py\", line 125, in main\r\n    client = influxdb.connect_to_influxdb()\r\n  File \"/tmp/ansible_KfqOgv/ansible_modlib.zip/ansible/module_utils/influxdb.py\", line 69, in connect_to_influxdb\r\nTypeError: __init__() got an unexpected keyword argument 'retries'\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def connect_to_influxdb(self):
    args = dict(
        host=self.hostname,
        port=self.port,
        username=self.username,
        password=self.password,
        database=self.database_name,
        ssl=self.params["ssl"],
        verify_ssl=self.params["validate_certs"],
        timeout=self.params["timeout"],
        use_udp=self.params["use_udp"],
        udp_port=self.params["udp_port"],
        proxies=self.params["proxies"],
    )
    influxdb_api_version = tuple(influxdb_version.split("."))
    if influxdb_api_version >= ("4", "1", "0"):
        # retries option is added in version 4.1.0
        args.update(retries=self.params["retries"])

    return InfluxDBClient(**args)
# Buggy code
def _update_check(self, entity):
    return (
        equal(self._module.params.get("description"), entity.description)
        and equal(self.param("quota_id"), getattr(entity.quota, "id"))
        and equal(
            convert_to_bytes(self._module.params.get("size")), entity.provisioned_size
        )
        and equal(self._module.params.get("shareable"), entity.shareable)
    )


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_JGGvK7/ansible_module_ovirt_disks.py", line 619, in main
fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL,
File "/tmp/ansible_JGGvK7/ansible_modlib.zip/ansible/module_utils/ovirt.py", line 601, in create
poll_interval=self._module.params['poll_interval'],
File "/tmp/ansible_JGGvK7/ansible_modlib.zip/ansible/module_utils/ovirt.py", line 330, in wait
elif fail_condition(entity):
File "/tmp/ansible_JGGvK7/ansible_module_ovirt_disks.py", line 619, in <lambda>
fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL,
AttributeError: 'NoneType' object has no attribute 'status'

# Fixed code
def _update_check(self, entity):
    return (
        equal(self._module.params.get("description"), entity.description)
        and equal(self.param("quota_id"), getattr(entity.quota, "id", None))
        and equal(
            convert_to_bytes(self._module.params.get("size")), entity.provisioned_size
        )
        and equal(self._module.params.get("shareable"), entity.shareable)
    )
# Buggy code
def __target_lun_map(self, storage):
    if storage.get("target"):
        lun_ids = (
            storage.get("lun_id")
            if isinstance(storage.get("lun_id"), list)
            else [(storage.get("lun_id"))]
        )
        return [(lun_id, storage.get("target")) for lun_id in lun_ids]
    elif storage.get("target_lun_map"):
        return [
            (target_map.get("lun_id"), target_map.get("target"))
            for target_map in storage.get("target_lun_map")
        ]


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_JGGvK7/ansible_module_ovirt_disks.py", line 619, in main
fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL,
File "/tmp/ansible_JGGvK7/ansible_modlib.zip/ansible/module_utils/ovirt.py", line 601, in create
poll_interval=self._module.params['poll_interval'],
File "/tmp/ansible_JGGvK7/ansible_modlib.zip/ansible/module_utils/ovirt.py", line 330, in wait
elif fail_condition(entity):
File "/tmp/ansible_JGGvK7/ansible_module_ovirt_disks.py", line 619, in <lambda>
fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL,
AttributeError: 'NoneType' object has no attribute 'status'

# Fixed code
def __target_lun_map(self, storage):
    if storage.get("target"):
        lun_ids = (
            storage.get("lun_id")
            if isinstance(storage.get("lun_id"), list)
            else [(storage.get("lun_id"))]
        )
        return [(lun_id, storage.get("target")) for lun_id in lun_ids]
    elif storage.get("target_lun_map"):
        return [
            (target_map.get("lun_id"), target_map.get("target"))
            for target_map in storage.get("target_lun_map")
        ]
    else:
        lun_ids = (
            storage.get("lun_id")
            if isinstance(storage.get("lun_id"), list)
            else [(storage.get("lun_id"))]
        )
        return [(lun_id, None) for lun_id in lun_ids]
# Buggy code
def __init__(self, module):
    super(SelfSignedCertificate, self).__init__(module)
    self.notBefore = module.params["selfsigned_notBefore"]
    self.notAfter = module.params["selfsigned_notAfter"]
    self.digest = module.params["selfsigned_digest"]
    self.version = module.params["selfsigned_version"]
    self.csr = crypto_utils.load_certificate_request(self.csr_path)
    self.privatekey = crypto_utils.load_privatekey(
        self.privatekey_path, self.privatekey_passphrase
    )


# Traceback (AttributeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'get_notBefore'

fatal: [phpmyadmin-ubuntu-artful]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 888, in <module>\n    main()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 862, in main\n    result = certificate.dump()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 484, in dump\n    'notBefore': self.cert.get_notBefore(),\nAttributeError: 'NoneType' object has no attribute 'get_notBefore'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def __init__(self, module):
    super(SelfSignedCertificate, self).__init__(module)
    self.notBefore = module.params["selfsigned_notBefore"]
    self.notAfter = module.params["selfsigned_notAfter"]
    self.digest = module.params["selfsigned_digest"]
    self.version = module.params["selfsigned_version"]
    self.serial_number = randint(1000, 99999)
    self.csr = crypto_utils.load_certificate_request(self.csr_path)
    self.privatekey = crypto_utils.load_privatekey(
        self.privatekey_path, self.privatekey_passphrase
    )
# Buggy code
def dump(self):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "csr": self.csr_path,
        "notBefore": self.cert.get_notBefore(),
        "notAfter": self.cert.get_notAfter(),
        "serial_number": self.cert.get_serial_number(),
    }

    return result


# Traceback (AttributeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'get_notBefore'

fatal: [phpmyadmin-ubuntu-artful]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 888, in <module>\n    main()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 862, in main\n    result = certificate.dump()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 484, in dump\n    'notBefore': self.cert.get_notBefore(),\nAttributeError: 'NoneType' object has no attribute 'get_notBefore'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def dump(self, check_mode=False):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "csr": self.csr_path,
    }

    if check_mode:
        now = datetime.datetime.utcnow()
        ten = now.replace(now.year + 10)
        result.update(
            {
                "notBefore": self.notBefore
                if self.notBefore
                else now.strftime("%Y%m%d%H%M%SZ"),
                "notAfter": self.notAfter
                if self.notAfter
                else ten.strftime("%Y%m%d%H%M%SZ"),
                "serial_number": self.serial_number,
            }
        )
    else:
        result.update(
            {
                "notBefore": self.cert.get_notBefore(),
                "notAfter": self.cert.get_notAfter(),
                "serial_number": self.cert.get_serial_number(),
            }
        )

    return result
# Buggy code
def dump(self):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "csr": self.csr_path,
    }

    return result


# Traceback (AttributeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'get_notBefore'

fatal: [phpmyadmin-ubuntu-artful]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 888, in <module>\n    main()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 862, in main\n    result = certificate.dump()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 484, in dump\n    'notBefore': self.cert.get_notBefore(),\nAttributeError: 'NoneType' object has no attribute 'get_notBefore'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def dump(self, check_mode=False):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "csr": self.csr_path,
    }

    return result
# Buggy code
def dump(self):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "accountkey": self.accountkey_path,
        "csr": self.csr_path,
    }

    return result


# Traceback (AttributeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'NoneType' object has no attribute 'get_notBefore'

fatal: [phpmyadmin-ubuntu-artful]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 888, in <module>\n    main()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 862, in main\n    result = certificate.dump()\n  File \"/tmp/ansible_wTx0Xq/ansible_module_openssl_certificate.py\", line 484, in dump\n    'notBefore': self.cert.get_notBefore(),\nAttributeError: 'NoneType' object has no attribute 'get_notBefore'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def dump(self, check_mode=False):
    result = {
        "changed": self.changed,
        "filename": self.path,
        "privatekey": self.privatekey_path,
        "accountkey": self.accountkey_path,
        "csr": self.csr_path,
    }

    return result
# Buggy code
def _parse_port_channels_summary(self, lag_type, lag_summary):
    if lag_type == self.MLAG_TYPE:
        lag_summary = lag_summary.get("MLAG Port-Channel Summary", {})
    for lag_key, lag_data in iteritems(lag_summary):
        lag_name, state = self._extract_lag_name(lag_key)
        if not lag_name:
            continue
        lag_members = self._extract_lag_members(lag_type, lag_data[0])
        lag_obj = dict(name=lag_name, state=state, members=lag_members)
        self._current_config[lag_name] = lag_obj


# Traceback (AttributeError)
TASK [leaf1 : configure MLag port channel with server 1] *************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'list' object has no attribute 'get'
fatal: [leaf1]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 338, in <module>\n main()\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 334, in main\n OnyxLinkAggModule.main()\n File \"/tmp/ansible_C2lxdf/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 240, in main\n File \"/tmp/ansible_C2lxdf/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 218, in run\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 248, in load_current_config\n self._parse_port_channels_summary(lag_type, lag_summary)\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 228, in _parse_port_channels_summary\n lag_summary = lag_summary.get('MLAG Port-Channel Summary', {})\nAttributeError: 'list' object has no attribute 'get'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
to retry, use: --limit @/etc/ansible/site.retry

# Fixed code
def _parse_port_channels_summary(self, lag_type, lag_summary):
    if lag_type == self.MLAG_TYPE:
        if self._os_version >= self.ONYX_API_VERSION:
            found_summary = False
            for summary_item in lag_summary:
                if self.MLAG_SUMMARY in summary_item:
                    lag_summary = summary_item[self.MLAG_SUMMARY]
                    if lag_summary:
                        lag_summary = lag_summary[0]
                    else:
                        lag_summary = dict()
                    found_summary = True
                    break
            if not found_summary:
                lag_summary = dict()
        else:
            lag_summary = lag_summary.get(self.MLAG_SUMMARY, dict())
    for lag_key, lag_data in iteritems(lag_summary):
        lag_name, state = self._extract_lag_name(lag_key)
        if not lag_name:
            continue
        lag_members = self._extract_lag_members(lag_type, lag_data[0])
        lag_obj = dict(name=lag_name, state=state, members=lag_members)
        self._current_config[lag_name] = lag_obj