gurudesh/pytracebugs huggingface dataset:
# Buggy code
def make_current_modifiable_param_dict(module, conn, name):
    """Gets the current state of the cache parameter group and creates a dict with the format: {ParameterName: [Allowed_Values, DataType, ParameterValue]}"""
    current_info = get_info(conn, name)
    if current_info is False:
        module.fail_json(
            msg="Could not connect to the cache parameter group %s." % name
        )

    parameters = current_info["Parameters"]
    modifiable_params = {}

    for param in parameters:
        if param["IsModifiable"] and ("AllowedValues" and "ParameterValue") in param:
            modifiable_params[param["ParameterName"]] = [
                param["AllowedValues"],
                param["DataType"],
                param["ParameterValue"],
            ]
    return modifiable_params


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 330, in <module>
main()
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 305, in main
modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 156, in make_current_modifiable_param_dict
modifiable_params[param["ParameterName"]] = [param["AllowedValues"], param["DataType"], param["ParameterValue"]]
KeyError: 'AllowedValues'

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 330, in <module>\n    main()\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 305, in main\n    modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 156, in make_current_modifiable_param_dict\n    modifiable_params[param[\"ParameterName\"]] = [param[\"AllowedValues\"], param[\"DataType\"], param[\"ParameterValue\"]]\nKeyError: 'AllowedValues'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def make_current_modifiable_param_dict(module, conn, name):
    """Gets the current state of the cache parameter group and creates a dict with the format: {ParameterName: [Allowed_Values, DataType, ParameterValue]}"""
    current_info = get_info(conn, name)
    if current_info is False:
        module.fail_json(
            msg="Could not connect to the cache parameter group %s." % name
        )

    parameters = current_info["Parameters"]
    modifiable_params = {}

    for param in parameters:
        if param["IsModifiable"]:
            modifiable_params[param["ParameterName"]] = [param.get("AllowedValues")]
            modifiable_params[param["ParameterName"]].append(param["DataType"])
            modifiable_params[param["ParameterName"]].append(
                param.get("ParameterValue")
            )
    return modifiable_params
# Buggy code
def modify(module, conn, name, values):
    """Modify ElastiCache parameter group to reflect the new information if it differs from the current."""
    # compares current group parameters with the parameters we've specified to to a value to see if this will change the group
    format_parameters = []
    for key in values:
        value = text_type(values[key])
        format_parameters.append({"ParameterName": key, "ParameterValue": value})
    try:
        response = conn.modify_cache_parameter_group(
            CacheParameterGroupName=name, ParameterNameValues=format_parameters
        )
    except botocore.exceptions.ClientError as e:
        module.fail_json(
            msg="Unable to modify cache parameter group.",
            exception=traceback.format_exc(),
            **camel_dict_to_snake_dict(e.response),
        )
    return response


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 330, in <module>
main()
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 305, in main
modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)
File "/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py", line 156, in make_current_modifiable_param_dict
modifiable_params[param["ParameterName"]] = [param["AllowedValues"], param["DataType"], param["ParameterValue"]]
KeyError: 'AllowedValues'

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 330, in <module>\n    main()\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 305, in main\n    modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)\n  File \"/tmp/ansible_wAJvSx/ansible_module_elasticache_parameter_group.py\", line 156, in make_current_modifiable_param_dict\n    modifiable_params[param[\"ParameterName\"]] = [param[\"AllowedValues\"], param[\"DataType\"], param[\"ParameterValue\"]]\nKeyError: 'AllowedValues'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def modify(module, conn, name, values):
    """Modify ElastiCache parameter group to reflect the new information if it differs from the current."""
    # compares current group parameters with the parameters we've specified to to a value to see if this will change the group
    format_parameters = []
    for key in values:
        value = to_text(values[key])
        format_parameters.append({"ParameterName": key, "ParameterValue": value})
    try:
        response = conn.modify_cache_parameter_group(
            CacheParameterGroupName=name, ParameterNameValues=format_parameters
        )
    except botocore.exceptions.ClientError as e:
        module.fail_json(
            msg="Unable to modify cache parameter group.",
            exception=traceback.format_exc(),
            **camel_dict_to_snake_dict(e.response),
        )
    return response
# Buggy code
def __init__(self, *args, **kwargs):
    super(Cli, self).__init__(*args, **kwargs)


# Traceback (AttributeError)
TASK [asa_pull_config : Fetching config from the remote node] ***************************************************************************************************************
task path: /home/actionmystique/Ansible/Roles/roles/asa_pull_config/tasks/main.yml:77
Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/network/asa/asa_command.py
<172.21.100.231> ESTABLISH LOCAL CONNECTION FOR USER: root
<172.21.100.231> EXEC /bin/sh -c '/usr/bin/python &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible__7xZ8h/ansible_module_asa_command.py", line 229, in <module>
main()
File "/tmp/ansible__7xZ8h/ansible_module_asa_command.py", line 180, in main
runner = CommandRunner(module)
File "/tmp/ansible__7xZ8h/ansible_modlib.zip/ansible/module_utils/netcli.py", line 140, in __init__
AttributeError: 'Cli' object has no attribute 'default_output'

fatal: [ASAv1]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible__7xZ8h/ansible_module_asa_command.py\", line 229, in <module>\n    main()\n  File \"/tmp/ansible__7xZ8h/ansible_module_asa_command.py\", line 180, in main\n    runner = CommandRunner(module)\n  File \"/tmp/ansible__7xZ8h/ansible_modlib.zip/ansible/module_utils/netcli.py\", line 140, in __init__\nAttributeError: 'Cli' object has no attribute 'default_output'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def __init__(self, *args, **kwargs):
    super(Cli, self).__init__(*args, **kwargs)
    self.default_output = "text"
# Buggy code
def execute_show_command(command, module, command_type="cli_show"):
    cmds = [command]
    if module.params["transport"] == "cli":
        body = run_commands(module, cmds)
    elif module.params["transport"] == "nxapi":
        body = run_commands(module, cmds)
    return body


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py", line 383, in <module>
main()
File "/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py", line 322, in main
existing = get_aaa_server_info(server_type, module)
File "/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py", line 197, in get_aaa_server_info
split_server = server_body.splitlines()
AttributeError: 'dict' object has no attribute 'splitlines'
FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py\", line 383, in <module>\n    main()\n  File \"/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py\", line 322, in main\n    existing = get_aaa_server_info(server_type, module)\n  File \"/tmp/ansible_eVPvvr/ansible_module_nxos_aaa_server.py\", line 197, in get_aaa_server_info\n    split_server = server_body.splitlines()\nAttributeError: 'dict' object has no attribute 'splitlines'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0

# Fixed code
def execute_show_command(command, module, command_type="cli_show"):
    command = {
        "command": command,
        "output": "text",
    }

    return run_commands(module, command)
# Buggy code
def execute_show_command(command, module, command_type="cli_show_ascii"):
    cmds = [command]
    if module.params["transport"] == "cli":
        body = run_commands(module, cmds)
    elif module.params["transport"] == "nxapi":
        body = run_commands(module, cmds)

    return body


# Traceback (nAttributeError)
fatal: [n9k.example.com]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_Zosdmt/ansible_module_nxos_snapshot.py\", line 476, in <module>\n    main()\n  File \"/tmp/ansible_Zosdmt/ansible_module_nxos_snapshot.py\", line 455, in main\n    final_snapshots = invoke('get_existing', module)\n  File \"/tmp/ansible_Zosdmt/ansible_module_nxos_snapshot.py\", line 356, in invoke\n    return func(*args, **kwargs)\n  File \"/tmp/ansible_Zosdmt/ansible_module_nxos_snapshot.py\", line 236, in get_existing\n    split_body = body.splitlines()\nAttributeError: 'dict' object has no attribute 'splitlines'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'dict' object has no attribute 'splitlines'

# Fixed code
def execute_show_command(command, module):
    command = [
        {
            "command": command,
            "output": "text",
        }
    ]

    return run_commands(module, command)
# Buggy code
def run(self, terms, inject=None, **kwargs):
    return [random.choice(terms)]


# Traceback (IndexError)
PLAYBOOK: random_choice.yml ****************************************************************************************************************************************************************************************************************************************************
1 plays in random_choice.yml

PLAY [localhost] ***************************************************************************************************************************************************************************************************************************************************************
META: ran handlers

TASK [Expected skip] ***********************************************************************************************************************************************************************************************************************************************************
task path: /Users/jean0000/evrardjp/ansible-pocs/random_choice.yml:9

TASK [Expected random item] ****************************************************************************************************************************************************************************************************************************************************
task path: /Users/jean0000/evrardjp/ansible-pocs/random_choice.yml:13
ok: [localhost] => (item=qwqwwqqw) => {
"item": "qwqwwqqw",
"msg": "qwqwwqqw"
}

TASK [Unexpected failure, not skipping] ****************************************************************************************************************************************************************************************************************************************
task path: /Users/jean0000/evrardjp/ansible-pocs/random_choice.yml:17
The full traceback is:
Traceback (most recent call last):
File "/Users/jean0000/.pip-apps/virtualenvs/ansible==2.3/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 89, in run
items = self._get_loop_items()
File "/Users/jean0000/.pip-apps/virtualenvs/ansible==2.3/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 214, in _get_loop_items
items = mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True)
File "/Users/jean0000/.pip-apps/virtualenvs/ansible==2.3/lib/python2.7/site-packages/ansible/plugins/lookup/random_choice.py", line 38, in run
return [ random.choice(terms) ]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

fatal: [localhost]: FAILED! => {
"failed": true,
"msg": "Unexpected failure during module execution.",
"stdout": ""
}

# Fixed code
def run(self, terms, inject=None, **kwargs):
    ret = terms
    if terms:
        try:
            ret = [random.choice(terms)]
        except Exception as e:
            raise AnsibleError("Unable to choose random term: %s" % to_native(e))

    return ret
# Buggy code
def find_vm_by_id(content, vm_id, vm_id_type="vm_name", datacenter=None, cluster=None):
    """UUID is unique to a VM, every other id returns the first match."""
    si = content.searchIndex
    vm = None

    if vm_id_type == "dns_name":
        vm = si.FindByDnsName(datacenter=datacenter, dnsName=vm_id, vmSearch=True)
    elif vm_id_type == "inventory_path":
        vm = si.FindByInventoryPath(inventoryPath=vm_id)
        if isinstance(vm, vim.VirtualMachine):
            vm = None
    elif vm_id_type == "uuid":
        vm = si.FindByUuid(datacenter=datacenter, instanceUuid=vm_id, vmSearch=True)
    elif vm_id_type == "ip":
        vm = si.FindByIp(datacenter=datacenter, ip=vm_id, vmSearch=True)
    elif vm_id_type == "vm_name":
        folder = None
        if cluster:
            folder = cluster
        elif datacenter:
            folder = datacenter.hostFolder
        vm = find_vm_by_name(content, vm_id, folder)

    return vm


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_xTG64q/ansible_module_vmware_guest_facts.py", line 236, in <module>
main()
File "/tmp/ansible_xTG64q/ansible_module_vmware_guest_facts.py", line 223, in main
uuid=module.params['uuid'])
File "/tmp/ansible_xTG64q/ansible_module_vmware_guest_facts.py", line 128, in getvm
vm = find_vm_by_id(self.content, vm_id=uuid, vm_id_type="uuid")
File "/tmp/ansible_xTG64q/ansible_modlib.zip/ansible/module_utils/vmware.py", line 182, in find_vm_by_id
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 580, in <lambda>
self.f(*(self.args + (obj,) + args), **kwargs)
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 385, in _InvokeMethod
list(map(CheckField, info.params, args))
File "/usr/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py", line 915, in CheckField
raise TypeError('Required field "%s" not provided (not @optional)' % info.name)
TypeError: Required field "uuid" not provided (not @optional)

# Fixed code
def find_vm_by_id(content, vm_id, vm_id_type="vm_name", datacenter=None, cluster=None):
    """UUID is unique to a VM, every other id returns the first match."""
    si = content.searchIndex
    vm = None

    if vm_id_type == "dns_name":
        vm = si.FindByDnsName(datacenter=datacenter, dnsName=vm_id, vmSearch=True)
    elif vm_id_type == "inventory_path":
        vm = si.FindByInventoryPath(inventoryPath=vm_id)
        if isinstance(vm, vim.VirtualMachine):
            vm = None
    elif vm_id_type == "uuid":
        # Search By BIOS UUID rather than instance UUID
        vm = si.FindByUuid(
            datacenter=datacenter, instanceUuid=False, uuid=vm_id, vmSearch=True
        )
    elif vm_id_type == "ip":
        vm = si.FindByIp(datacenter=datacenter, ip=vm_id, vmSearch=True)
    elif vm_id_type == "vm_name":
        folder = None
        if cluster:
            folder = cluster
        elif datacenter:
            folder = datacenter.hostFolder
        vm = find_vm_by_name(content, vm_id, folder)

    return vm
# Buggy code
def user_and_group(self, path, expand=True):
    b_path = to_bytes(path, errors="surrogate_then_strict")
    if expand:
        b_path = os.path.expanduser(os.path.expandvars(b_path))
    st = os.lstat(b_path)
    uid = st.st_uid
    gid = st.st_gid
    return (uid, gid)


# Traceback (LookupError)
exception:
Traceback (most recent call last):
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 480, in <module>
main()
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 362, in main
changed |= recursive_set_attributes(module, to_bytes(file_args['path'], errors='surrogate_or_strict'), follow, file_args)
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 171, in recursive_set_attributes
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed)
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 1292, in set_fs_attributes_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 995, in set_owner_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/_text.py", line 232, in to_text
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
LookupError: unknown error handler name 'surrogate_then_strict'

# Fixed code
def user_and_group(self, path, expand=True):
    b_path = to_bytes(path, errors="surrogate_or_strict")
    if expand:
        b_path = os.path.expanduser(os.path.expandvars(b_path))
    st = os.lstat(b_path)
    uid = st.st_uid
    gid = st.st_gid
    return (uid, gid)
# Buggy code
def get_hash(data, hashtype="sha1"):
    try:  # see if hash is supported
        h = hashlib.new(hashtype)
    except:
        return None

    h.update(to_bytes(data, errors="surrogate_then_strict"))
    return h.hexdigest()


# Traceback (LookupError)
exception:
Traceback (most recent call last):
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 480, in <module>
main()
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 362, in main
changed |= recursive_set_attributes(module, to_bytes(file_args['path'], errors='surrogate_or_strict'), follow, file_args)
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 171, in recursive_set_attributes
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed)
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 1292, in set_fs_attributes_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 995, in set_owner_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/_text.py", line 232, in to_text
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
LookupError: unknown error handler name 'surrogate_then_strict'

# Fixed code
def get_hash(data, hashtype="sha1"):
    try:  # see if hash is supported
        h = hashlib.new(hashtype)
    except:
        return None

    h.update(to_bytes(data, errors="surrogate_or_strict"))
    return h.hexdigest()
# Buggy code
def b64encode(string):
    return to_text(base64.b64encode(to_bytes(string, errors="surrogate_then_strict")))


# Traceback (LookupError)
exception:
Traceback (most recent call last):
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 480, in <module>
main()
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 362, in main
changed |= recursive_set_attributes(module, to_bytes(file_args['path'], errors='surrogate_or_strict'), follow, file_args)
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 171, in recursive_set_attributes
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed)
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 1292, in set_fs_attributes_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 995, in set_owner_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/_text.py", line 232, in to_text
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
LookupError: unknown error handler name 'surrogate_then_strict'

# Fixed code
def b64encode(string):
    return to_text(base64.b64encode(to_bytes(string, errors="surrogate_or_strict")))
# Buggy code
def b64decode(string):
    return to_text(base64.b64decode(to_bytes(string, errors="surrogate_then_strict")))


# Traceback (LookupError)
exception:
Traceback (most recent call last):
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 480, in <module>
main()
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 362, in main
changed |= recursive_set_attributes(module, to_bytes(file_args['path'], errors='surrogate_or_strict'), follow, file_args)
File "/tmp/ansible_atAUEE/ansible_module_file.py", line 171, in recursive_set_attributes
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed)
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 1292, in set_fs_attributes_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/basic.py", line 995, in set_owner_if_different
File "/tmp/ansible_atAUEE/ansible_modlib.zip/ansible/module_utils/_text.py", line 232, in to_text
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
LookupError: unknown error handler name 'surrogate_then_strict'

# Fixed code
def b64decode(string):
    return to_text(base64.b64decode(to_bytes(string, errors="surrogate_or_strict")))
# Buggy code
def __init__(self, block=None, role=None, task_include=None):
    super(IncludeRole, self).__init__(block=block, role=role, task_include=task_include)

    self._from_files = {}
    self._parent_role = role
    self._role_name = None


# Traceback (AttributeError)
TASK [foo : include] **************************************************************************************************************************************************************************
task path: /tmp/demo/roles/foo/tasks/main.yml:2
ERROR! Unexpected Exception, this is probably a bug: 'NoneType' object has no attribute 'rfind'
the full traceback was:

Traceback (most recent call last):
File "/home/spredzy/Projects/github.com/Spredzy/ansible/bin/ansible-playbook", line 106, in <module>
exit_code = cli.run()
File "/home/spredzy/Projects/github.com/Spredzy/ansible/lib/ansible/cli/playbook.py", line 130, in run
results = pbex.run()
File "/home/spredzy/Projects/github.com/Spredzy/ansible/lib/ansible/executor/playbook_executor.py", line 153, in run
result = self._tqm.run(play=play)
File "/home/spredzy/Projects/github.com/Spredzy/ansible/lib/ansible/executor/task_queue_manager.py", line 285, in run
play_return = strategy.run(iterator, play_context)
File "/home/spredzy/Projects/github.com/Spredzy/ansible/lib/ansible/plugins/strategy/linear.py", line 331, in run
variable_manager=self._variable_manager
File "/home/spredzy/Projects/github.com/Spredzy/ansible/lib/ansible/playbook/included_file.py", line 104, in process_include_results
parent_include_dir = os.path.dirname(templar.template(parent_include.args.get('_raw_params')))
File "/usr/lib64/python2.7/posixpath.py", line 122, in dirname
i = p.rfind('/') + 1
AttributeError: 'NoneType' object has no attribute 'rfind'

# Fixed code
def __init__(self, block=None, role=None, task_include=None):
    super(IncludeRole, self).__init__(block=block, role=role, task_include=task_include)

    self._from_files = {}
    self._parent_role = role
    self._role_name = None
    self._role_path = None
# Buggy code
def get_defaults_flag(module):
    rc, out, err = exec_command(module, "show running-config ?")
    out = to_text(out, errors="surrogate_then_replace")

    commands = set()
    for line in out.splitlines():
        if line:
            commands.add(line.strip().split()[0])

    if "all" in commands:
        return "all"
    else:
        return "full"


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 530, in <module>
main()
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 438, in main
config, have_banners = get_running_config(module, config)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 347, in get_running_config
contents = get_config(module, flags=flags)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py", line 85, in get_config
TypeError: can only join an iterable

fatal: [ios01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 530, in <module>\n    main()\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 438, in main\n    config, have_banners = get_running_config(module, config)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 347, in get_running_config\n    contents = get_config(module, flags=flags)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py\", line 85, in get_config\nTypeError: can only join an iterable\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_defaults_flag(module):
    rc, out, err = exec_command(module, "show running-config ?")
    out = to_text(out, errors="surrogate_then_replace")

    commands = set()
    for line in out.splitlines():
        if line.strip():
            commands.add(line.strip().split()[0])

    if "all" in commands:
        return ["all"]
    else:
        return ["full"]
# Buggy code
def get_running_config(module, current_config=None):
    contents = module.params["running_config"]
    if not contents:
        if not module.params["defaults"] and current_config:
            contents, banners = extract_banners(current_config.config_text)
        else:
            flags = get_defaults_flag(module) if module.params["defaults"] else None
            contents = get_config(module, flags=flags)
    contents, banners = extract_banners(contents)
    return NetworkConfig(indent=1, contents=contents), banners


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 530, in <module>
main()
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 438, in main
config, have_banners = get_running_config(module, config)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 347, in get_running_config
contents = get_config(module, flags=flags)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py", line 85, in get_config
TypeError: can only join an iterable

fatal: [ios01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 530, in <module>\n    main()\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 438, in main\n    config, have_banners = get_running_config(module, config)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 347, in get_running_config\n    contents = get_config(module, flags=flags)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py\", line 85, in get_config\nTypeError: can only join an iterable\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_running_config(module, current_config=None):
    contents = module.params["running_config"]
    if not contents:
        if not module.params["defaults"] and current_config:
            contents, banners = extract_banners(current_config.config_text)
        else:
            flags = get_defaults_flag(module) if module.params["defaults"] else []
            contents = get_config(module, flags=flags)
    contents, banners = extract_banners(contents)
    return NetworkConfig(indent=1, contents=contents), banners
# Buggy code
def get_defaults_flag(module):
    rc, out, err = exec_command(module, "show running-config ?")

    commands = set()
    for line in out.splitlines():
        if line:
            commands.add(line.strip().split()[0])

    if "all" in commands:
        return "all"
    else:
        return "full"


# Traceback (TypeError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 530, in <module>
main()
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 438, in main
config, have_banners = get_running_config(module, config)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py", line 347, in get_running_config
contents = get_config(module, flags=flags)
File "/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py", line 85, in get_config
TypeError: can only join an iterable

fatal: [ios01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 530, in <module>\n    main()\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 438, in main\n    config, have_banners = get_running_config(module, config)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_module_ios_config.py\", line 347, in get_running_config\n    contents = get_config(module, flags=flags)\n  File \"/var/folders/ql/d9_087wj4cd10grvwzxmk4hc0000gn/T/ansible_XWMNMk/ansible_modlib.zip/ansible/module_utils/ios.py\", line 85, in get_config\nTypeError: can only join an iterable\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_defaults_flag(module):
    rc, out, err = exec_command(module, "show running-config ?")

    commands = set()
    for line in out.splitlines():
        if line.strip():
            commands.add(line.strip().split()[0])

    if "all" in commands:
        return ["all"]
    else:
        return ["full"]
# Buggy code
def apply_key_map(key_map, table):
    new_dict = {}
    for key, value in table.items():
        new_key = key_map.get(key)
        if new_key:
            value = table.get(key)
            if value:
                new_dict[new_key] = value
            else:
                new_dict[new_key] = value
    return new_dict


# Traceback (TypeError)
ansible-playbook site.yml -l core7k-a --check -t configure_interface_ospf -vvv

PLAYBOOK: site.yml *************************************************************************************************************************
2 plays in site.yml

PLAY [localhost] ***************************************************************************************************************************
skipping: no hosts matched

PLAY [nxos] ********************************************************************************************************************************
META: ran handlers

TASK [configure interface ospf] ************************************************************************************************************
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_9nZ5Pe/ansible_module_nxos_interface_ospf.py", line 540, in <module>
main()
File "/tmp/ansible_9nZ5Pe/ansible_module_nxos_interface_ospf.py", line 523, in main
result.update(response)
TypeError: 'NoneType' object is not iterable

fatal: [core7k-a]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_9nZ5Pe/ansible_module_nxos_interface_ospf.py\", line 540, in <module>\n    main()\n  File \"/tmp/ansible_9nZ5Pe/ansible_module_nxos_interface_ospf.py\", line 523, in main\n    result.update(response)\nTypeError: 'NoneType' object is not iterable\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

PLAY RECAP *********************************************************************************************************************************
core7k-a               : ok=0    changed=0    unreachable=0    failed=1

# Fixed code
def apply_key_map(key_map, table):
    new_dict = {}
    for key, value in table.items():
        new_key = key_map.get(key)
        if new_key:
            new_dict[new_key] = value
    return new_dict
# Buggy code
def contains(self, key):
    self._expire_keys()
    return self._cache.zrank(self._keys_set, key) >= 0


# Traceback (TypeError)
petr@tabor ~> python2 -c 'value = None; print(value > 0)'
False
petr@tabor ~> python3 -c 'value = None; print(value > 0)'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: '>' not supported between instances of 'NoneType' and 'int'
petr@tabor ~> python3 -c 'value = None; print(value is not None and value > 0)'
False

# Fixed code
def contains(self, key):
    self._expire_keys()
    return self._cache.zrank(self._keys_set, key) is not None
# Buggy code
def _create_stack(module, stack, cloud):
    try:
        stack = cloud.create_stack(
            module.params["name"],
            template_file=module.params["template"],
            environment_files=module.params["environment"],
            timeout=module.params["timeout"],
            wait=True,
            rollback=module.params["rollback"],
            **module.params["parameters"],
        )

        stack = cloud.get_stack(stack.id, None)
        if stack.stack_status == "CREATE_COMPLETE":
            return stack
        else:
            return False
            module.fail_json(msg="Failure in creating stack: {0}".format(stack))
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))


# Traceback (AttributeError)
Traceback (most recent call last):
File "/tmp/ansible_pfxIaX/ansible_module_os_stack.py", line 262, in <module>
main()
File "/tmp/ansible_pfxIaX/ansible_module_os_stack.py", line 247, in main
id=stack.id)
AttributeError: 'bool' object has no attribute 'id'

# Fixed code
def _create_stack(module, stack, cloud):
    try:
        stack = cloud.create_stack(
            module.params["name"],
            template_file=module.params["template"],
            environment_files=module.params["environment"],
            timeout=module.params["timeout"],
            wait=True,
            rollback=module.params["rollback"],
            **module.params["parameters"],
        )

        stack = cloud.get_stack(stack.id, None)
        if stack.stack_status == "CREATE_COMPLETE":
            return stack
        else:
            module.fail_json(msg="Failure in creating stack: {0}".format(stack))
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
# Buggy code
def delete_bucket(module, s3, bucket):
    if module.check_mode:
        module.exit_json(
            msg="DELETE operation skipped - running in check mode", changed=True
        )
    try:
        bucket = s3.lookup(bucket)
        bucket_contents = bucket.list()
        bucket.delete_keys([key.name for key in bucket_contents])
        bucket.delete()
        return True
    except s3.provider.storage_response_error as e:
        module.fail_json(msg=str(e))


# Traceback (nAttributeError)
fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/mk/zyr99n9j3dg3tlqp__8xqp_0kbzv15/T/ansible_15ONhL/ansible_module_s3.py\", line 765, in <module>\n    main()\n  File \"/var/folders/mk/zyr99n9j3dg3tlqp__8xqp_0kbzv15/T/ansible_15ONhL/ansible_module_s3.py\", line 651, in main\n    deletertn = delete_bucket(module, s3, bucket)\n  File \"/var/folders/mk/zyr99n9j3dg3tlqp__8xqp_0kbzv15/T/ansible_15ONhL/ansible_module_s3.py\", line 340, in delete_bucket\n    bucket_contents = bucket.list()\nAttributeError: 'NoneType' object has no attribute 'list'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def delete_bucket(module, s3, bucket):
    if module.check_mode:
        module.exit_json(
            msg="DELETE operation skipped - running in check mode", changed=True
        )
    try:
        bucket = s3.lookup(bucket, validate=False)
        bucket_contents = bucket.list()
        bucket.delete_keys([key.name for key in bucket_contents])
    except s3.provider.storage_response_error as e:
        if e.status == 404:
            # bucket doesn't appear to exist
            return False
        elif e.status == 403:
            # bucket appears to exist but user doesn't have list bucket permission; may still be able to delete bucket
            pass
        else:
            module.fail_json(msg=str(e), exception=traceback.format_exc())
    try:
        bucket.delete()
        return True
    except s3.provider.storage_response_error as e:
        if e.status == 403:
            module.exit_json(
                msg="Unable to complete DELETE operation. Check you have have s3:DeleteBucket "
                "permission. Error: {0}.".format(e.message),
                exception=traceback.format_exc(),
            )
        elif e.status == 409:
            module.exit_json(
                msg="Unable to complete DELETE operation. It appears there are contents in the "
                "bucket that you don't have permission to delete. Error: {0}.".format(
                    e.message
                ),
                exception=traceback.format_exc(),
            )
        else:
            module.fail_json(msg=str(e), exception=traceback.format_exc())
# Buggy code
def _check_type_jsonarg(self, value):
    # Return a jsonified string.  Sometimes the controller turns a json
    # string into a dict/list so transform it back into json here
    if isinstance(value, (text_type, binary_type)):
        return value.strip()
    else:
        if isinstance(value, (list, tuple, dict)):
            return json.dumps(value)
    raise TypeError("%s cannot be converted to a json string" % type(value))


# Traceback (RuntimeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: RuntimeError: maximum recursion depth exceeded in cmp
fatal: [trd-gw]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):
File \"/tmp/ansible_4P2WOB/ansible_module_junos_facts.py\", line 757, in <module>
main()
File \"/tmp/ansible_4P2WOB/ansible_module_junos_facts.py\", line 753, in main
module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 1983, in exit_json
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 1973, in _return_formatted
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
[---- SNIP ----]
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 411, in remove_values
File \"/usr/lib/python2.7/abc.py\", line 141, in __instancecheck__
subtype in cls._abc_negative_cache):
File \"/usr/lib/python2.7/_weakrefset.py\", line 75, in __contains__
return wr in self.data
RuntimeError: maximum recursion depth exceeded in cmp
", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def _check_type_jsonarg(self, value):
    # Return a jsonified string.  Sometimes the controller turns a json
    # string into a dict/list so transform it back into json here
    if isinstance(value, (text_type, binary_type)):
        return value.strip()
    else:
        if isinstance(value, (list, tuple, dict)):
            return self.jsonify(value)
    raise TypeError("%s cannot be converted to a json string" % type(value))
# Buggy code
def jsonify(self, data):
    for encoding in ("utf-8", "latin-1"):
        try:
            return json.dumps(data, encoding=encoding)
        # Old systems using old simplejson module does not support encoding keyword.
        except TypeError:
            try:
                new_data = json_dict_bytes_to_unicode(data, encoding=encoding)
            except UnicodeDecodeError:
                continue
            return json.dumps(new_data)
        except UnicodeDecodeError:
            continue
    self.fail_json(msg="Invalid unicode encoding encountered")


# Traceback (RuntimeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: RuntimeError: maximum recursion depth exceeded in cmp
fatal: [trd-gw]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):
File \"/tmp/ansible_4P2WOB/ansible_module_junos_facts.py\", line 757, in <module>
main()
File \"/tmp/ansible_4P2WOB/ansible_module_junos_facts.py\", line 753, in main
module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 1983, in exit_json
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 1973, in _return_formatted
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in remove_values
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 414, in <genexpr>
[---- SNIP ----]
File \"/tmp/ansible_4P2WOB/ansible_modlib.zip/ansible/module_utils/basic.py\", line 411, in remove_values
File \"/usr/lib/python2.7/abc.py\", line 141, in __instancecheck__
subtype in cls._abc_negative_cache):
File \"/usr/lib/python2.7/_weakrefset.py\", line 75, in __contains__
return wr in self.data
RuntimeError: maximum recursion depth exceeded in cmp
", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def jsonify(self, data):
    for encoding in ("utf-8", "latin-1"):
        try:
            return json.dumps(data, encoding=encoding, cls=_SetEncoder)
        # Old systems using old simplejson module does not support encoding keyword.
        except TypeError:
            try:
                new_data = json_dict_bytes_to_unicode(data, encoding=encoding)
            except UnicodeDecodeError:
                continue
            return json.dumps(new_data, cls=_SetEncoder)
        except UnicodeDecodeError:
            continue
    self.fail_json(msg="Invalid unicode encoding encountered")
# Buggy code
def write_changes(module, contents, path):
    tmpfd, tmpfile = tempfile.mkstemp()
    f = os.fdopen(tmpfd, "wb")
    f.write(to_bytes(contents))
    f.close()

    validate = module.params.get("validate", None)
    valid = not validate
    if validate:
        if "%s" not in validate:
            module.fail_json(msg="validate must contain %%s: %s" % (validate))
        (rc, out, err) = module.run_command(validate % tmpfile)
        valid = rc == 0
        if rc != 0:
            module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err))
    if valid:
        module.atomic_move(tmpfile, path, unsafe_writes=module.params["unsafe_writes"])


# Traceback (UnicodeDecodeError)
failed: [myhost.domain.tld] (item={u'regexp': u'pattern', u'replace': u'new_value'}) => {"failed": true, "item": {"regexp": "pattern", "replace": "new_value"}, "module_stderr": "Shared connection to myhost.domain.tld closed.
", "module_stdout": "Traceback (most recent call last):
File \"/tmp/ansible_D5fUnl/ansible_module_replace.py\", line 200, in <module>
main()
File \"/tmp/ansible_D5fUnl/ansible_module_replace.py\", line 169, in main
contents = to_text(f.read(), errors='surrogate_or_strict')
File \"/tmp/ansible_D5fUnl/ansible_modlib.zip/ansible/module_utils/_text.py\", line 232, in to_text
File \"/usr/lib/python2.7/encodings/utf_8.py\", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd6 in position 114: invalid continuation byte
", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def write_changes(module, contents, path):
    tmpfd, tmpfile = tempfile.mkstemp()
    f = os.fdopen(tmpfd, "wb")
    f.write(contents)
    f.close()

    validate = module.params.get("validate", None)
    valid = not validate
    if validate:
        if "%s" not in validate:
            module.fail_json(msg="validate must contain %%s: %s" % (validate))
        (rc, out, err) = module.run_command(validate % tmpfile)
        valid = rc == 0
        if rc != 0:
            module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err))
    if valid:
        module.atomic_move(tmpfile, path, unsafe_writes=module.params["unsafe_writes"])
# Buggy code
def is_systemd_managed(self, module):
    # tools must be installed
    if module.get_bin_path("systemctl"):
        # this should show if systemd is the boot init system, if checking init faild to mark as systemd
        # these mirror systemd's own sd_boot test http://www.freedesktop.org/software/systemd/man/sd_booted.html
        for canary in ["/run/systemd/system/", "/dev/.run/systemd/", "/dev/.systemd/"]:
            if os.path.exists(canary):
                return True
    return False


# Traceback (NameError)
74024 1496367398.68545: _low_level_execute_command() done: rc=0, stdout=
Traceback (most recent call last):
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 766, in <module>
main()
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 755, in main
hostname = Hostname(module)
File "/tmp/ansible_OtWEyM/ansible_module_hostname.py", line 115, in __init__
if self.platform == 'Linux' and Facts(module).is_systemd_managed():
NameError: global name 'Facts' is not defined
, stderr=OpenSSH_7.4p1, LibreSSL 2.5.0

# Fixed code
def is_systemd_managed(module):
    # tools must be installed
    if module.get_bin_path("systemctl"):
        # this should show if systemd is the boot init system, if checking init faild to mark as systemd
        # these mirror systemd's own sd_boot test http://www.freedesktop.org/software/systemd/man/sd_booted.html
        for canary in ["/run/systemd/system/", "/dev/.run/systemd/", "/dev/.systemd/"]:
            if os.path.exists(canary):
                return True
    return False