gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _load_vars_prompt(self, attr, ds):
    new_ds = preprocess_vars(ds)
    vars_prompts = []
    for prompt_data in new_ds:
        if "name" not in prompt_data:
            display.deprecated(
                "Using the 'short form' for vars_prompt has been deprecated",
                version="2.7",
            )
            for vname, prompt in prompt_data.items():
                vars_prompts.append(
                    dict(
                        name=vname,
                        prompt=prompt,
                        default=None,
                        private=None,
                        confirm=None,
                        encrypt=None,
                        salt_size=None,
                        salt=None,
                    )
                )
        else:
            vars_prompts.append(prompt_data)
    return vars_prompts


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/ansible/src/ansible/bin/ansible-playbook", line 109, in <module>
exit_code = cli.run()
File "/home/ansible/src/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/ansible/src/ansible/lib/ansible/executor/playbook_executor.py", line 82, in run
pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader)
File "/home/ansible/src/ansible/lib/ansible/playbook/__init__.py", line 54, in load
pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager)
File "/home/ansible/src/ansible/lib/ansible/playbook/__init__.py", line 106, in _load_playbook_data
entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader)
File "/home/ansible/src/ansible/lib/ansible/playbook/play.py", line 112, in load
return p.load_data(data, variable_manager=variable_manager, loader=loader)
File "/home/ansible/src/ansible/lib/ansible/playbook/base.py", line 252, in load_data
self._attributes[target_name] = method(name, ds[name])
File "/home/ansible/src/ansible/lib/ansible/playbook/play.py", line 199, in _load_vars_prompt
for prompt_data in new_ds:
TypeError: 'NoneType' object is not iterable

# Fixed code
def _load_vars_prompt(self, attr, ds):
    new_ds = preprocess_vars(ds)
    vars_prompts = []
    if new_ds is not None:
        for prompt_data in new_ds:
            if "name" not in prompt_data:
                display.deprecated(
                    "Using the 'short form' for vars_prompt has been deprecated",
                    version="2.7",
                )
                for vname, prompt in prompt_data.items():
                    vars_prompts.append(
                        dict(
                            name=vname,
                            prompt=prompt,
                            default=None,
                            private=None,
                            confirm=None,
                            encrypt=None,
                            salt_size=None,
                            salt=None,
                        )
                    )
            else:
                vars_prompts.append(prompt_data)
    return vars_prompts
# Buggy code
def load_rules_from_file(self):
    self.fname = self.path + "/" + self.name
    stringline = ""
    try:
        for line in open(self.fname, "r"):
            stringline += line.rstrip()
            stringline += "\n"
        self.load_rules_from_string(stringline)

    except IOError:
        e = get_exception()
        self.ansible.fail_json(
            msg="Unable to open/read PAM module \
                                   file %s with error %s.  And line %s"
            % (self.fname, str(e), stringline)
        )


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 651, in <module>
main()
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 606, in main
pamd.load_rules_from_file()
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 328, in load_rules_from_file
self.load_rules_from_string(stringline)
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 344, in load_rules_from_string
self.rules.append(PamdRule.rulefromstring(stringline))
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 279, in rulefromstring
rule_type = result.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

# Fixed code
def load_rules_from_file(self):
    self.fname = os.path.join(self.path, self.name)
    stringline = ""
    try:
        for line in open(self.fname, "r"):
            stringline += line.rstrip().lstrip()
            stringline += "\n"
        self.load_rules_from_string(stringline.replace("\\\n", ""))

    except IOError:
        e = get_exception()
        self.ansible.fail_json(
            msg="Unable to open/read PAM module \
                                   file %s with error %s.  And line %s"
            % (self.fname, str(e), stringline)
        )
# Buggy code
def load_rules_from_string(self, stringvalue):
    for line in stringvalue.splitlines():
        stringline = line.rstrip()
        if line.startswith("#") and not line.isspace():
            self.preamble.append(line.rstrip())
        elif not line.startswith("#") and not line.isspace() and len(line) != 0:
            self.rules.append(PamdRule.rulefromstring(stringline))


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 651, in <module>
main()
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 606, in main
pamd.load_rules_from_file()
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 328, in load_rules_from_file
self.load_rules_from_string(stringline)
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 344, in load_rules_from_string
self.rules.append(PamdRule.rulefromstring(stringline))
File "/tmp/ansible_TpFc0r/ansible_module_pamd.py", line 279, in rulefromstring
rule_type = result.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

# Fixed code
def load_rules_from_string(self, stringvalue):
    for line in stringvalue.splitlines():
        stringline = line.rstrip()
        if line.startswith("#") and not line.isspace():
            self.preamble.append(line.rstrip())
        elif not line.startswith("#") and not line.isspace() and len(line) != 0:
            try:
                self.ansible.log(msg="Creating rule from string %s" % stringline)
            except AttributeError:
                pass
            self.rules.append(PamdRule.rulefromstring(stringline))
# Buggy code
def send_command(self, command, prompt=None, answer=None, sendonly=False, newline=True):
    """Executes a cli command and returns the results
    This method will execute the CLI command on the connection and return
    the results to the caller.  The command output will be returned as a
    string
    """
    kwargs = {"command": to_bytes(command), "sendonly": sendonly, "newline": newline}
    if prompt is not None:
        kwargs["prompt"] = to_bytes(prompt)
    if answer is not None:
        kwargs["answer"] = to_bytes(answer)

    resp = self._connection.send(**kwargs)
    return resp


# Traceback (ConnectionError)
TASK [Config Using Core Module] ************************************************************************************************************************************************************
task path: /Users/gnalawad/targets/ios_interface.yml:21
<ios> attempting to start connection
<ios> using connection plugin network_cli
<ios> found existing local domain socket, using it!
<ios>
The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: 'NoneType' object has no attribute 'endswith'

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "'NoneType' object has no attribute 'endswith'"


The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: unable to elevate privilege to enable mode, at prompt [None]

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "unable to elevate privilege to enable mode, at prompt [None]"
}

# Fixed code
def send_command(
    self,
    command,
    prompt=None,
    answer=None,
    sendonly=False,
    newline=True,
    prompt_retry_check=False,
):
    """Executes a cli command and returns the results
    This method will execute the CLI command on the connection and return
    the results to the caller.  The command output will be returned as a
    string
    """
    kwargs = {
        "command": to_bytes(command),
        "sendonly": sendonly,
        "newline": newline,
        "prompt_retry_check": prompt_retry_check,
    }
    if prompt is not None:
        kwargs["prompt"] = to_bytes(prompt)
    if answer is not None:
        kwargs["answer"] = to_bytes(answer)

    resp = self._connection.send(**kwargs)
    return resp
# Buggy code
def send(self, command, prompt=None, answer=None, newline=True, sendonly=False):
    """
    Sends the command to the device in the opened shell
    """
    try:
        self._history.append(command)
        self._ssh_shell.sendall(b"%s\r" % command)
        if sendonly:
            return
        response = self.receive(command, prompt, answer, newline)
        return to_text(response, errors="surrogate_or_strict")
    except (socket.timeout, AttributeError):
        display.vvvv(traceback.format_exc(), host=self._play_context.remote_addr)
        raise AnsibleConnectionFailure(
            "timeout trying to send command: %s" % command.strip()
        )


# Traceback (ConnectionError)
TASK [Config Using Core Module] ************************************************************************************************************************************************************
task path: /Users/gnalawad/targets/ios_interface.yml:21
<ios> attempting to start connection
<ios> using connection plugin network_cli
<ios> found existing local domain socket, using it!
<ios>
The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: 'NoneType' object has no attribute 'endswith'

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "'NoneType' object has no attribute 'endswith'"


The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: unable to elevate privilege to enable mode, at prompt [None]

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "unable to elevate privilege to enable mode, at prompt [None]"
}

# Fixed code
def send(
    self,
    command,
    prompt=None,
    answer=None,
    newline=True,
    sendonly=False,
    prompt_retry_check=False,
):
    """
    Sends the command to the device in the opened shell
    """
    try:
        self._history.append(command)
        self._ssh_shell.sendall(b"%s\r" % command)
        if sendonly:
            return
        response = self.receive(command, prompt, answer, newline, prompt_retry_check)
        return to_text(response, errors="surrogate_or_strict")
    except (socket.timeout, AttributeError):
        display.vvvv(traceback.format_exc(), host=self._play_context.remote_addr)
        raise AnsibleConnectionFailure(
            "timeout trying to send command: %s" % command.strip()
        )
# Buggy code
def on_become(self, passwd=None):
    if self._get_prompt().endswith(b"#"):
        return

    cmd = {"command": "enable"}
    if passwd:
        cmd["prompt"] = to_text(r"[\r\n]?password: $", errors="surrogate_or_strict")
        cmd["answer"] = passwd

    try:
        self._exec_cli_command(to_bytes(json.dumps(cmd), errors="surrogate_or_strict"))
    except AnsibleConnectionFailure:
        raise AnsibleConnectionFailure("unable to elevate privilege to enable mode")


# Traceback (ConnectionError)
TASK [Config Using Core Module] ************************************************************************************************************************************************************
task path: /Users/gnalawad/targets/ios_interface.yml:21
<ios> attempting to start connection
<ios> using connection plugin network_cli
<ios> found existing local domain socket, using it!
<ios>
The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: 'NoneType' object has no attribute 'endswith'

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "'NoneType' object has no attribute 'endswith'"


The full traceback is:
Traceback (most recent call last):
File "/Users/home/ansible/bin/ansible-connection", line 253, in main
messages.extend(conn.update_play_context(pc_data))
File "/Users/home/ansible/lib/ansible/module_utils/connection.py", line 146, in __rpc__
raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)
ConnectionError: unable to elevate privilege to enable mode, at prompt [None]

fatal: [ios]: FAILED! => {
"failed": true,
"msg": "unable to elevate privilege to enable mode, at prompt [None]"
}

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

    cmd = {"command": "enable"}
    if passwd:
        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)
        )
# Buggy code
def assume_role_policy(connection, module):
    role_arn = module.params.get("role_arn")
    role_session_name = module.params.get("role_session_name")
    policy = module.params.get("policy")
    duration_seconds = module.params.get("duration_seconds")
    external_id = module.params.get("external_id")
    mfa_serial_number = module.params.get("mfa_serial_number")
    mfa_token = module.params.get("mfa_token")
    changed = False

    try:
        assumed_role = connection.assume_role(
            role_arn,
            role_session_name,
            policy,
            duration_seconds,
            external_id,
            mfa_serial_number,
            mfa_token,
        )
        changed = True
    except BotoServerError as e:
        module.fail_json(msg=e)

    module.exit_json(
        changed=changed,
        sts_creds=assumed_role.credentials.__dict__,
        sts_user=assumed_role.user.__dict__,
    )


# Traceback (nTypeError)
TASK [******** : Assume role] ******************************************
fatal: [10.0.50.110]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 10.0.50.110 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 153, in <module>\r\n    main()\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 147, in main\r\n    assume_role_policy(connection, module)\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 110, in assume_role_policy\r\n    assumed_role = connection.assume_role(role_arn, role_session_name, policy, duration_seconds, external_id, mfa_serial_number, mfa_token)\r\nTypeError: assume_role() takes at most 6 arguments (8 given)\r\n", "msg": "MODULE FAILURE"}

# Fixed code
def assume_role_policy(connection, module):
    params = {
        "RoleArn": module.params.get("role_arn"),
        "RoleSessionName": module.params.get("role_session_name"),
        "Policy": module.params.get("policy"),
        "DurationSeconds": module.params.get("duration_seconds"),
        "ExternalId": module.params.get("external_id"),
        "SerialNumber": module.params.get("mfa_serial_number"),
        "TokenCode": module.params.get("mfa_token"),
    }
    changed = False

    kwargs = dict((k, v) for k, v in params.items() if v is not None)

    try:
        response = connection.assume_role(**kwargs)
        changed = True
    except (ClientError, ParamValidationError) as e:
        module.fail_json_aws(e)

    sts_cred, sts_user = _parse_response(response)
    module.exit_json(changed=changed, sts_creds=sts_cred, sts_user=sts_user)
# Buggy code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            role_arn=dict(required=True, default=None),
            role_session_name=dict(required=True, default=None),
            duration_seconds=dict(required=False, default=None, type="int"),
            external_id=dict(required=False, default=None),
            policy=dict(required=False, default=None),
            mfa_serial_number=dict(required=False, default=None),
            mfa_token=dict(required=False, default=None),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg="boto required for this module")

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.sts, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    try:
        assume_role_policy(connection, module)
    except BotoServerError as e:
        module.fail_json(msg=e)


# Traceback (nTypeError)
TASK [******** : Assume role] ******************************************
fatal: [10.0.50.110]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to 10.0.50.110 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 153, in <module>\r\n    main()\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 147, in main\r\n    assume_role_policy(connection, module)\r\n  File \"/tmp/ansible_yTSWAA/ansible_module_sts_assume_role.py\", line 110, in assume_role_policy\r\n    assumed_role = connection.assume_role(role_arn, role_session_name, policy, duration_seconds, external_id, mfa_serial_number, mfa_token)\r\nTypeError: assume_role() takes at most 6 arguments (8 given)\r\n", "msg": "MODULE FAILURE"}

# Fixed code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            role_arn=dict(required=True, default=None),
            role_session_name=dict(required=True, default=None),
            duration_seconds=dict(required=False, default=None, type="int"),
            external_id=dict(required=False, default=None),
            policy=dict(required=False, default=None),
            mfa_serial_number=dict(required=False, default=None),
            mfa_token=dict(required=False, default=None),
        )
    )

    module = AnsibleAWSModule(argument_spec=argument_spec)

    region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)

    if region:
        connection = boto3_conn(
            module,
            conn_type="client",
            resource="sts",
            region=region,
            endpoint=ec2_url,
            **aws_connect_kwargs,
        )

    else:
        module.fail_json(msg="region must be specified")

    assume_role_policy(connection, module)
# Buggy code
def _register(self, key):
    try:
        # We have to perform the one-time registration here. Otherwise, we receive an error the first
        # time we attempt to use the requested client.
        resource_client = self.rm_client
        resource_client.providers.register(key)
    except Exception as exc:
        self.fail("One-time registration of {0} failed - {1}".format(key, str(exc)))


# Traceback (Exception)
azure config mode arm
azure login
azure group create ansible-inventory-example northeurope
azure ad app create --name ansible-inventory-adapp --password XXXX --identifier-uris http://ansible-inventory-adapp --home-page http://ansible-inventory-adapp
azure ad sp create --applicationId XXXXXX-XXXX-XXXX-XXXX-XXXXXXX
azure role assignment create --roleName Owner --spn http://ansible-inventory-adapp --resource-group ansible-inventory-example

wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/azure_rm.py
python azure_rm.py --subscription_id XXXXXXXXXXXXX --secret XXXXXXXXXXXx --tenant XXXXXXXXX --client_id XXXXXXXXXX --resource-groups ansible-inventory-example

Traceback (most recent call last):
File "azure_rm.py", line 798, in <module>
main()
File "azure_rm.py", line 795, in main
AzureInventory()
File "azure_rm.py", line 402, in __init__
self._compute_client = rm.compute_client
File "azure_rm.py", line 387, in compute_client
self._register('Microsoft.Compute')
File "azure_rm.py", line 365, in _register
self.fail("One-time registration of {0} failed - {1}".format(key, str(exc)))
File "azure_rm.py", line 287, in fail
raise Exception(msg)
Exception: One-time registration of Microsoft.Compute failed - The client 'XXXXXXXXXXXX' with object id 'XXXXXXXXXX' does not have authorization to perform action 'Microsoft.Compute/register/action' over scope '/subscriptions/XXXXXXXXXXXXXXXX'.

# Fixed code
def _register(self, key):
    try:
        # We have to perform the one-time registration here. Otherwise, we receive an error the first
        # time we attempt to use the requested client.
        resource_client = self.rm_client
        resource_client.providers.register(key)
    except Exception as exc:
        self.log("One-time registration of {0} failed - {1}".format(key, str(exc)))
        self.log("You might need to register {0} using an admin account".format(key))
        self.log(
            (
                "To register a provider using the Python CLI: "
                "https://docs.microsoft.com/azure/azure-resource-manager/"
                "resource-manager-common-deployment-errors#noregisteredproviderfound"
            )
        )
# Buggy code
def get_virtual_gateway_info(virtual_gateway):
    virtual_gateway_info = {
        "VpnGatewayId": virtual_gateway["VpnGatewayId"],
        "State": virtual_gateway["State"],
        "Type": virtual_gateway["Type"],
        "VpcAttachments": virtual_gateway["VpcAttachments"],
        "Tags": virtual_gateway["Tags"],
    }
    return virtual_gateway_info


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py", line 174, in <module>
main()
File "/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py", line 168, in main
results = list_virtual_gateways(connection, module)
File "/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py", line 141, in list_virtual_gateways
for vgw in all_virtual_gateways['VpnGateways']]
File "/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py", line 112, in get_virtual_gateway_info
'Tags': virtual_gateway['Tags']}
KeyError: 'Tags'

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py\", line 174, in <module>\n    main()\n  File \"/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py\", line 168, in main\n    results = list_virtual_gateways(connection, module)\n  File \"/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py\", line 141, in list_virtual_gateways\n    for vgw in all_virtual_gateways['VpnGateways']]\n  File \"/tmp/ansible_c6AWJi/ansible_module_ec2_vpc_vgw_facts.py\", line 112, in get_virtual_gateway_info\n    **'Tags': virtual_gateway['Tags']}\nKeyError: 'Tags'**\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_virtual_gateway_info(virtual_gateway):
    virtual_gateway_info = {
        "VpnGatewayId": virtual_gateway["VpnGatewayId"],
        "State": virtual_gateway["State"],
        "Type": virtual_gateway["Type"],
        "VpcAttachments": virtual_gateway["VpcAttachments"],
        "Tags": virtual_gateway.get("Tags", []),
    }
    return virtual_gateway_info
# Buggy code
def enable_mode(func):
    @wraps(func)
    def wrapped(self, *args, **kwargs):
        prompt = self.get_prompt()
        if not str(prompt).strip().endswith("#"):
            raise AnsibleError("operation requires privilege escalation")
        return func(self, *args, **kwargs)

    return wrapped


# Traceback (nansible.module_utils.connection.ConnectionError)
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_module_vyos_command.py\", line 233, in <module>\n    main()\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_module_vyos_command.py\", line 203, in main\n    responses = run_commands(module, commands)\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 104, in run_commands\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 70, in get_connection\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 84, in get_capabilities\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/connection.py\", line 146, in __rpc__\nansible.module_utils.connection.ConnectionError: operation requires privilege escalation\n",

# Fixed code
def enable_mode(func):
    @wraps(func)
    def wrapped(self, *args, **kwargs):
        prompt = self._connection.get_prompt()
        if not to_text(prompt, errors="surrogate_or_strict").strip().endswith("#"):
            raise AnsibleError("operation requires privilege escalation")
        return func(self, *args, **kwargs)

    return wrapped
# Buggy code
def wrapped(self, *args, **kwargs):
    prompt = self.get_prompt()
    if not str(prompt).strip().endswith("#"):
        raise AnsibleError("operation requires privilege escalation")
    return func(self, *args, **kwargs)


# Traceback (nansible.module_utils.connection.ConnectionError)
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_module_vyos_command.py\", line 233, in <module>\n    main()\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_module_vyos_command.py\", line 203, in main\n    responses = run_commands(module, commands)\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 104, in run_commands\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 70, in get_connection\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/network/vyos/vyos.py\", line 84, in get_capabilities\n  File \"/Users/gnalawad/targets/ansible_ChpCiX/ansible_modlib.zip/ansible/module_utils/connection.py\", line 146, in __rpc__\nansible.module_utils.connection.ConnectionError: operation requires privilege escalation\n",

# Fixed code
def wrapped(self, *args, **kwargs):
    prompt = self._connection.get_prompt()
    if not to_text(prompt, errors="surrogate_or_strict").strip().endswith("#"):
        raise AnsibleError("operation requires privilege escalation")
    return func(self, *args, **kwargs)
# Buggy code
def down_connection(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # if self.connection_exists():
    cmd.append("con")
    cmd.append("down")
    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 down_connection(self):
    cmd = [self.nmcli_bin, "con", "down", self.conn_name]
    # if self.connection_exists():
    return self.execute_command(cmd)
# Buggy code
def up_connection(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    cmd.append("con")
    cmd.append("up")
    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 up_connection(self):
    cmd = [self.nmcli_bin, "con", "up", self.conn_name]
    return self.execute_command(cmd)
# Buggy code
def create_connection_team(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating team interface
    cmd.append("con")
    cmd.append("add")
    cmd.append("type")
    cmd.append("team")
    cmd.append("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)
    if self.ip4 is not None:
        cmd.append("ip4")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("gw4")
        cmd.append(self.gw4)
    if self.ip6 is not None:
        cmd.append("ip6")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("gw6")
        cmd.append(self.gw6)
    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 create_connection_team(self):
    cmd = [self.nmcli_bin, "con", "add", "type", "team", "con-name"]
    # format for creating team interface
    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)
    if self.ip4 is not None:
        cmd.append("ip4")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("gw4")
        cmd.append(self.gw4)
    if self.ip6 is not None:
        cmd.append("ip6")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("gw6")
        cmd.append(self.gw6)
    if self.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
    return cmd
# Buggy code
def modify_connection_team(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying team interface
    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.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
        # Can't use MTU with team
    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_team(self):
    cmd = [self.nmcli_bin, "con", "mod", self.conn_name]
    # format for modifying team interface
    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.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
        # Can't use MTU with team
    return cmd
# Buggy code
def create_connection_team_slave(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating team-slave interface
    cmd.append("connection")
    cmd.append("add")
    cmd.append("type")
    cmd.append(self.type)
    cmd.append("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)
    cmd.append("master")
    if self.conn_name is not None:
        cmd.append(self.master)
    # if self.mtu is not None:
    #     cmd.append('802-3-ethernet.mtu')
    #     cmd.append(self.mtu)
    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_team_slave(self):
    cmd = [self.nmcli_bin, "connection", "add", "type", self.type, "con-name"]
    # format for creating team-slave interface
    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)
    cmd.append("master")
    if self.conn_name is not None:
        cmd.append(self.master)
    # if self.mtu is not None:
    #     cmd.append('802-3-ethernet.mtu')
    #     cmd.append(self.mtu)
    return cmd
# Buggy code
def modify_connection_team_slave(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying team-slave interface
    cmd.append("con")
    cmd.append("mod")
    cmd.append(self.conn_name)
    cmd.append("connection.master")
    cmd.append(self.master)
    if self.mtu is not None:
        cmd.append("802-3-ethernet.mtu")
        cmd.append(self.mtu)
    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_team_slave(self):
    cmd = [
        self.nmcli_bin,
        "con",
        "mod",
        self.conn_name,
        "connection.master",
        self.master,
    ]
    # format for modifying team-slave interface
    if self.mtu is not None:
        cmd.append("802-3-ethernet.mtu")
        cmd.append(self.mtu)
    return cmd
# Buggy code
def modify_connection_bond(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying bond interface
    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.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_bond(self):
    cmd = [self.nmcli_bin, "con", "mod", self.conn_name]
    # format for modifying bond interface
    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.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
    return cmd
# Buggy code
def create_connection_bond_slave(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating bond-slave interface
    cmd.append("connection")
    cmd.append("add")
    cmd.append("type")
    cmd.append("bond-slave")
    cmd.append("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)
    cmd.append("master")
    if self.conn_name is not None:
        cmd.append(self.master)
    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_bond_slave(self):
    cmd = [self.nmcli_bin, "connection", "add", "type", "bond-slave", "con-name"]
    # format for creating bond-slave interface
    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)
    cmd.append("master")
    if self.conn_name is not None:
        cmd.append(self.master)
    return cmd
# Buggy code
def modify_connection_bond_slave(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for modifying bond-slave interface
    cmd.append("con")
    cmd.append("mod")
    cmd.append(self.conn_name)
    cmd.append("connection.master")
    cmd.append(self.master)
    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_bond_slave(self):
    cmd = [
        self.nmcli_bin,
        "con",
        "mod",
        self.conn_name,
        "connection.master",
        self.master,
    ]
    # format for modifying bond-slave interface
    return cmd
# Buggy code
def create_connection_ethernet(self):
    cmd = [self.module.get_bin_path("nmcli", True)]
    # format for creating 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("add")
    cmd.append("type")
    cmd.append("ethernet")
    cmd.append("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)
    if self.ip4 is not None:
        cmd.append("ip4")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("gw4")
        cmd.append(self.gw4)
    if self.ip6 is not None:
        cmd.append("ip6")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("gw6")
        cmd.append(self.gw6)
    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 create_connection_ethernet(self):
    cmd = [self.nmcli_bin, "con", "add", "type", "ethernet", "con-name"]
    # format for creating 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.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)
    if self.ip4 is not None:
        cmd.append("ip4")
        cmd.append(self.ip4)
    if self.gw4 is not None:
        cmd.append("gw4")
        cmd.append(self.gw4)
    if self.ip6 is not None:
        cmd.append("ip6")
        cmd.append(self.ip6)
    if self.gw6 is not None:
        cmd.append("gw6")
        cmd.append(self.gw6)
    if self.autoconnect is not None:
        cmd.append("autoconnect")
        cmd.append(self.bool_to_string(self.autoconnect))
    return cmd