gurudesh/pytracebugs huggingface dataset:
# Buggy code
def semanage_port_get_type(seport, port, proto):
    """Get the SELinux type of the specified port.

    :param seport: Instance of seobject.portRecords

    :type port: str
    :param port: Port or port range (example: "8080", "8080-9090")

    :type proto: str
    :param proto: Protocol ('tcp' or 'udp')

    :rtype: tuple
    :return: Tuple containing the SELinux type and MLS/MCS level, or None if not found.
    """
    ports = port.split("-", 1)
    if len(ports) == 1:
        ports.extend(ports)
    key = (int(ports[0]), int(ports[1]), proto)

    records = seport.get_all()
    if key in records:
        return records[key]
    else:
        return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 114, in <module>
File "<stdin>", line 106, in _ansiballz_main
File "<stdin>", line 49, in invoke_module
File "/tmp/ansible_seport_payload_EvYc5a/__main__.py", line 307, in <module>
File "/tmp/ansible_seport_payload_EvYc5a/__main__.py", line 297, in main
File "/tmp/ansible_seport_payload_EvYc5a/__main__.py", line 206, in semanage_port_add
File "/tmp/ansible_seport_payload_EvYc5a/__main__.py", line 159, in semanage_port_get_type
AttributeError: 'int' object has no attribute 'split'

# Fixed code
def semanage_port_get_type(seport, port, proto):
    """Get the SELinux type of the specified port.

    :param seport: Instance of seobject.portRecords

    :type port: str
    :param port: Port or port range (example: "8080", "8080-9090")

    :type proto: str
    :param proto: Protocol ('tcp' or 'udp')

    :rtype: tuple
    :return: Tuple containing the SELinux type and MLS/MCS level, or None if not found.
    """
    if isinstance(port, str):
        ports = port.split("-", 1)
        if len(ports) == 1:
            ports.extend(ports)
    else:
        ports = (port, port)

    key = (int(ports[0]), int(ports[1]), proto)

    records = seport.get_all()
    if key in records:
        return records[key]
    else:
        return None
# Buggy code
def filter(self, record):
    return not any(f.filter(record) for f in self.blacklist)


# Traceback (KeyError)
ansible 2.9.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/etsadm/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /bin/ansible
python version = 2.7.5 (default, Jun 11 2019, 14:33:56) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
Using /etc/ansible/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /etc/ansible/hosts/generaInventario.sh as it did not pass its verify_file() method
Parsed /etc/ansible/hosts/generaInventario.sh inventory source with script plugin
Loading callback plugin minimal of type stdout, v2.0 from /usr/lib/python2.7/site-packages/ansible/plugins/callback/minimal.pyc
META: ran handlers
Using module file /usr/lib/python2.7/site-packages/ansible/modules/windows/win_ping.ps1
Pipelining is enabled.
<windows_node_client> ESTABLISH WINRM CONNECTION FOR USER: None on PORT 5986 TO windows_node_client
Traceback (most recent call last):
File "/usr/lib64/python2.7/logging/__init__.py", line 851, in emit
msg = self.format(record)
File "/usr/lib64/python2.7/logging/__init__.py", line 724, in format
return fmt.format(record)
File "/usr/lib64/python2.7/logging/__init__.py", line 467, in format
s = self._fmt % record.__dict__
KeyError: 'user'
Logged from file connectionpool.py, line 735
EXEC (via pipeline wrapper)
windows_node_client | SUCCESS => {
"changed": false,
"invocation": {
"module_args": {
"data": "pong"
}
},
"ping": "pong"
}
META: ran handlers
META: ran handlers

# Fixed code
def filter(self, record):
    record.user = FilterUserInjector.username
    return True
# Buggy code
def _is_module_installed(self, module_spec):
    if self.with_modules:
        module_spec = module_spec.strip()
        module_list, nsv = self.module_base._get_modules(module_spec)

        if nsv.stream in self.base._moduleContainer.getEnabledStream(nsv.name):
            return True

    return False  # seems like a sane default


# Traceback (nAttributeError)
centos8 | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to 10.4.2.130 closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n  File \"/usr/lib/python3.6/site-packages/dnf/plugin.py\", line 102, in _caller\r\n    getattr(plugin, method)()\r\n  File \"/usr/lib/python3.6/site-packages/dnf-plugins/spacewalk.py\", line 84, in config\r\n    self.cli.demands.root_user = True\r\nAttributeError: 'NoneType' object has no attribute 'demands'\r\n\r\nTraceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 114, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 106, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1571403585.19-28589661305719/AnsiballZ_dnf.py\", line 49, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/usr/lib64/python3.6/imp.py\", line 235, in load_module\r\n    return load_source(name, filename, file)\r\n  File \"/usr/lib64/python3.6/imp.py\", line 170, in load_source\r\n    module = _exec(spec, sys.modules[name])\r\n  File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1322, in <module>\r\n  File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1311, in main\r\n  File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 1290, in run\r\n  File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 957, in ensure\r\n  File \"/tmp/ansible_dnf_payload_wsyb0smr/__main__.py\", line 890, in _is_module_installed\r\nTypeError: 'in <string>' requires string as left operand, not NoneType\r\n",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}

# Fixed code
def _is_module_installed(self, module_spec):
    if self.with_modules:
        module_spec = module_spec.strip()
        module_list, nsv = self.module_base._get_modules(module_spec)
        enabled_streams = self.base._moduleContainer.getEnabledStream(nsv.name)

        if enabled_streams:
            if nsv.stream:
                if nsv.stream in enabled_streams:
                    return True  # The provided stream was found
                else:
                    return False  # The provided stream was not found
            else:
                return True  # No stream provided, but module found

    return False  # seems like a sane default
# Buggy code
def snow_argument_spec():
    return dict(
        instance=dict(type="str", required=True),
        username=dict(type="str", required=True),
        password=dict(type="str", required=True, no_log=True),
        client_id=dict(type="str", no_log=True),
        client_secret=dict(type="str", no_log=True),
    )


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'

# Fixed code
def snow_argument_spec():
    return dict(
        instance=dict(
            type="str", required=False, fallback=(env_fallback, ["SN_INSTANCE"])
        ),
        username=dict(
            type="str", required=False, fallback=(env_fallback, ["SN_USERNAME"])
        ),
        password=dict(
            type="str",
            required=False,
            no_log=True,
            fallback=(env_fallback, ["SN_PASSWORD"]),
        ),
        client_id=dict(type="str", no_log=True),
        client_secret=dict(type="str", no_log=True),
    )
# Buggy code
def to_dict(items, key, value):
    """Transforms a list of items to a Key/Value dictionary"""
    if items:
        return dict(zip([i[key] for i in items], [i[value] for i in items]))
    else:
        return dict()


# Traceback (KeyError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: KeyError: 'PhysicalResourceId'
fatal: [localhost]: FAILED! => {
"changed": false,
"rc": 1
}

MSG:

MODULE FAILURE


MODULE_STDERR:

Traceback (most recent call last):
File "/tmp/ansible_6yPBHl/ansible_module_cloudformation_facts.py", line 318, in <module>
main()
File "/tmp/ansible_6yPBHl/ansible_module_cloudformation_facts.py", line 303, in main
facts['stack_resources'] = to_dict(facts.get('stack_resource_list'), 'LogicalResourceId', 'PhysicalResourceId')
File "/tmp/ansible_6yPBHl/ansible_module_cloudformation_facts.py", line 261, in to_dict
return dict(zip([i[key] for i in items], [i[value] for i in items]))
KeyError: 'PhysicalResourceId'

# Fixed code
def to_dict(items, key, value):
    """Transforms a list of items to a Key/Value dictionary"""
    if items:
        return dict(zip([i.get(key) for i in items], [i.get(value) for i in items]))
    else:
        return dict()
# Buggy code
def _connect(self):
    """connect to the chroot; nothing to do here"""
    super(Connection, self)._connect()
    if not self._connected:
        display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
        self._connected = True


# Traceback (AttributeError)
ansible 2.8.2
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.13 (default, Sep 26 2018, 18:42:22) [GCC 6.3.0 20170516]
Using /etc/ansible/ansible.cfg as config file
Unable to parse address from hostname, leaving unchanged: Not a valid network hostname: /target
Parsed /target, inventory source with host_list plugin
META: ran handlers
The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 144, in run
res = self._execute()
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 590, in _execute
self._connection = self._get_connection(variables=variables, templar=templar)
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 892, in _get_connection
ansible_playbook_pid=to_text(os.getppid())
File "/usr/lib/python2.7/dist-packages/ansible/plugins/loader.py", line 579, in get
obj = obj(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/ansible/plugins/connection/chroot.py", line 99, in __init__
if os.path.isabs(self.get_option('chroot_exe')):
File "/usr/lib/python2.7/dist-packages/ansible/plugins/__init__.py", line 58, in get_option
option_value = C.config.get_config_value(option, plugin_type=get_plugin_class(self), plugin_name=self._load_name, variables=hostvars)
AttributeError: 'Connection' object has no attribute '_load_name'

/target | FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}

# Fixed code
def _connect(self):
    """connect to the chroot"""
    if os.path.isabs(self.get_option("chroot_exe")):
        self.chroot_cmd = self.get_option("chroot_exe")
    else:
        self.chroot_cmd = get_bin_path(self.get_option("chroot_exe"))

    if not self.chroot_cmd:
        raise AnsibleError(
            "chroot command (%s) not found in PATH"
            % to_native(self.get_option("chroot_exe"))
        )

    super(Connection, self)._connect()
    if not self._connected:
        display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
        self._connected = True
# Buggy code
def is_image_name_id(name):
    """Checks whether the given image name is in fact an image ID (hash)."""
    if re.match("^sha256:[0-9a-fA-F]{64}$", name):
        return True
    return False


# Traceback (requests.exceptions.ConnectionError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: requests.exceptions.ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
fatal: [buster_local_docker]: FAILED! => changed=false
module_stderr: |-
Traceback (most recent call last):
File "/tmp/.ansible/tmp/ansible-tmp-1562335690.251731-79429560017149/AnsiballZ_docker_image.py", line 114, in <module>
_ansiballz_main()
File "/tmp/.ansible/tmp/ansible-tmp-1562335690.251731-79429560017149/AnsiballZ_docker_image.py", line 106, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/tmp/.ansible/tmp/ansible-tmp-1562335690.251731-79429560017149/AnsiballZ_docker_image.py", line 49, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_docker_image_payload_jIHMqS/__main__.py", line 926, in <module>
File "/tmp/ansible_docker_image_payload_jIHMqS/__main__.py", line 921, in main
File "/tmp/ansible_docker_image_payload_jIHMqS/__main__.py", line 476, in __init__
File "/tmp/ansible_docker_image_payload_jIHMqS/__main__.py", line 504, in present
File "/tmp/ansible_docker_image_payload_jIHMqS/__main__.py", line 731, in build_image
File "/usr/local/lib/python2.7/dist-packages/docker/api/build.py", line 269, in build
timeout=timeout,
File "/usr/local/lib/python2.7/dist-packages/docker/utils/decorators.py", line 46, in inner
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/docker/api/client.py", line 226, in _post
return self.post(url, **self._set_request_timeout(kwargs))
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 581, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
module_stdout: ''
msg: |-
MODULE FAILURE
See stdout/stderr for the exact error
rc: 1

# Fixed code
def is_image_name_id(name):
    """Check whether the given image name is in fact an image ID (hash)."""
    if re.match("^sha256:[0-9a-fA-F]{64}$", name):
        return True
    return False
# Buggy code
def modify_connection_vlan(self):
    cmd = [self.nmcli_bin]
    cmd.append("con")
    cmd.append("mod")

    if self.conn_name is not None:
        cmd.append(self.conn_name)
    elif self.ifname is not None:
        cmd.append(self.ifname)
    else:
        cmd.append("vlan%s" % self.vlanid)

    params = {
        "vlan.parent": self.vlandev,
        "vlan.id": self.vlanid,
        "ipv4.address": self.ip4 or "",
        "ipv4.gateway": self.gw4 or "",
        "ipv4.dns": self.dns4 or "",
        "ipv6.address": self.ip6 or "",
        "ipv6.gateway": self.gw6 or "",
        "ipv6.dns": self.dns6 or "",
        "autoconnect": self.bool_to_string(self.autoconnect),
    }

    for k, v in params.items():
        cmd.extend([k, v])

    return cmd


# Traceback (nTypeError)
TASK [Add Vlan 120] ************************************************************
task path: /root/ansible/vlan.yaml:5
fatal: [192.168.122.144]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "module_stderr": "Shared connection to 192.168.122.144 closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1562811604.6034448-71465935769547/AnsiballZ_nmcli.py\", line 114, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1562811604.6034448-71465935769547/AnsiballZ_nmcli.py\", line 106, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1562811604.6034448-71465935769547/AnsiballZ_nmcli.py\", line 49, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/tmp/ansible_nmcli_payload_divn_m/__main__.py\", line 1549, in <module>\r\n  File \"/tmp/ansible_nmcli_payload_divn_m/__main__.py\", line 1532, in main\r\n  File \"/tmp/ansible_nmcli_payload_divn_m/__main__.py\", line 1388, in create_connection\r\n  File \"/tmp/ansible_nmcli_payload_divn_m/__main__.py\", line 682, in execute_command\r\n  File \"/tmp/ansible_nmcli_payload_divn_m/ansible_nmcli_payload.zip/ansible/module_utils/basic.py\", line 2477, in run_command\r\n  File \"/usr/lib64/python2.7/posixpath.py\", line 293, in expandvars\r\n    if '$' not in path:\r\nTypeError: argument of type 'int' is not iterable\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def modify_connection_vlan(self):
    cmd = [self.nmcli_bin]
    cmd.append("con")
    cmd.append("mod")

    if self.conn_name is not None:
        cmd.append(self.conn_name)
    elif self.ifname is not None:
        cmd.append(self.ifname)
    else:
        cmd.append("vlan%s" % self.vlanid)

    params = {
        "vlan.parent": self.vlandev,
        "vlan.id": str(self.vlanid),
        "ipv4.address": self.ip4 or "",
        "ipv4.gateway": self.gw4 or "",
        "ipv4.dns": self.dns4 or "",
        "ipv6.address": self.ip6 or "",
        "ipv6.gateway": self.gw6 or "",
        "ipv6.dns": self.dns6 or "",
        "autoconnect": self.bool_to_string(self.autoconnect),
    }

    for k, v in params.items():
        cmd.extend([k, v])

    return cmd
# Buggy code
def _get_snapshot_starttime(snap):
    return datetime.datetime.strptime(snap.start_time, "%Y-%m-%dT%H:%M:%S.000Z")


# Traceback (ValueError)
The full traceback is:
Traceback (most recent call last):
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 114, in <module>
_ansiballz_main()
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 106, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 49, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 304, in <module>
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 299, in main
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 226, in create_snapshot
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 147, in _get_most_recent_snapshot
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 129, in _get_snapshot_starttime
File "/usr/lib64/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2019-05-27T12:08:49.929Z' does not match format '%Y-%m-%dT%H:%M:%S.000Z'

# Fixed code
def _get_snapshot_starttime(snap):
    return datetime.datetime.strptime(snap.start_time, "%Y-%m-%dT%H:%M:%S.%fZ")
# Buggy code
def _get_most_recent_snapshot(snapshots, max_snapshot_age_secs=None, now=None):
    """
    Gets the most recently created snapshot and optionally filters the result
    if the snapshot is too old
    :param snapshots: list of snapshots to search
    :param max_snapshot_age_secs: filter the result if its older than this
    :param now: simulate time -- used for unit testing
    :return:
    """
    if len(snapshots) == 0:
        return None

    if not now:
        now = datetime.datetime.utcnow()

    youngest_snapshot = max(snapshots, key=_get_snapshot_starttime)

    # See if the snapshot is younger that the given max age
    snapshot_start = datetime.datetime.strptime(
        youngest_snapshot.start_time, "%Y-%m-%dT%H:%M:%S.000Z"
    )
    snapshot_age = now - snapshot_start

    if max_snapshot_age_secs is not None:
        if snapshot_age.total_seconds() > max_snapshot_age_secs:
            return None

    return youngest_snapshot


# Traceback (ValueError)
The full traceback is:
Traceback (most recent call last):
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 114, in <module>
_ansiballz_main()
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 106, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/root/.ansible/tmp/ansible-tmp-1559010783.94-53825915141864/AnsiballZ_ec2_snapshot.py", line 49, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 304, in <module>
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 299, in main
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 226, in create_snapshot
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 147, in _get_most_recent_snapshot
File "/tmp/ansible_ec2_snapshot_payload_XOjcWn/__main__.py", line 129, in _get_snapshot_starttime
File "/usr/lib64/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2019-05-27T12:08:49.929Z' does not match format '%Y-%m-%dT%H:%M:%S.000Z'

# Fixed code
def _get_most_recent_snapshot(snapshots, max_snapshot_age_secs=None, now=None):
    """
    Gets the most recently created snapshot and optionally filters the result
    if the snapshot is too old
    :param snapshots: list of snapshots to search
    :param max_snapshot_age_secs: filter the result if its older than this
    :param now: simulate time -- used for unit testing
    :return:
    """
    if len(snapshots) == 0:
        return None

    if not now:
        now = datetime.datetime.utcnow()

    youngest_snapshot = max(snapshots, key=_get_snapshot_starttime)

    # See if the snapshot is younger that the given max age
    snapshot_start = datetime.datetime.strptime(
        youngest_snapshot.start_time, "%Y-%m-%dT%H:%M:%S.%fZ"
    )
    snapshot_age = now - snapshot_start

    if max_snapshot_age_secs is not None:
        if snapshot_age.total_seconds() > max_snapshot_age_secs:
            return None

    return youngest_snapshot
# Buggy code
def __init__(self, src, dest, file_args, module):
    self.src = src
    self.dest = dest
    self.file_args = file_args
    self.opts = module.params["extra_opts"]
    self.module = module
    self.excludes = module.params["exclude"]
    self.includes = []
    self.cmd_path = self.module.get_bin_path("unzip")
    self.zipinfocmd_path = self.module.get_bin_path("zipinfo")
    self._files_in_archive = []
    self._infodict = dict()


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __init__(self, src, b_dest, file_args, module):
    self.src = src
    self.b_dest = b_dest
    self.file_args = file_args
    self.opts = module.params["extra_opts"]
    self.module = module
    self.excludes = module.params["exclude"]
    self.includes = []
    self.cmd_path = self.module.get_bin_path("unzip")
    self.zipinfocmd_path = self.module.get_bin_path("zipinfo")
    self._files_in_archive = []
    self._infodict = dict()
# Buggy code
def unarchive(self):
    cmd = [self.cmd_path, "-o"]
    if self.opts:
        cmd.extend(self.opts)
    cmd.append(self.src)
    # NOTE: Including (changed) files as arguments is problematic (limits on command line/arguments)
    # if self.includes:
    # NOTE: Command unzip has this strange behaviour where it expects quoted filenames to also be escaped
    # cmd.extend(map(shell_escape, self.includes))
    if self.excludes:
        cmd.extend(["-x"] + self.excludes)
    cmd.extend(["-d", self.dest])
    rc, out, err = self.module.run_command(cmd)
    return dict(cmd=cmd, rc=rc, out=out, err=err)


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def unarchive(self):
    cmd = [self.cmd_path, "-o"]
    if self.opts:
        cmd.extend(self.opts)
    cmd.append(self.src)
    # NOTE: Including (changed) files as arguments is problematic (limits on command line/arguments)
    # if self.includes:
    # NOTE: Command unzip has this strange behaviour where it expects quoted filenames to also be escaped
    # cmd.extend(map(shell_escape, self.includes))
    if self.excludes:
        cmd.extend(["-x"] + self.excludes)
    cmd.extend(["-d", self.b_dest])
    rc, out, err = self.module.run_command(cmd)
    return dict(cmd=cmd, rc=rc, out=out, err=err)
# Buggy code
def unarchive(self):
    cmd = [self.cmd_path, "--extract", "-C", self.dest]
    if self.zipflag:
        cmd.append(self.zipflag)
    if self.opts:
        cmd.extend(["--show-transformed-names"] + self.opts)
    if self.file_args["owner"]:
        cmd.append("--owner=" + quote(self.file_args["owner"]))
    if self.file_args["group"]:
        cmd.append("--group=" + quote(self.file_args["group"]))
    if self.module.params["keep_newer"]:
        cmd.append("--keep-newer-files")
    if self.excludes:
        cmd.extend(["--exclude=" + f for f in self.excludes])
    cmd.extend(["-f", self.src])
    rc, out, err = self.module.run_command(
        cmd, cwd=self.dest, environ_update=dict(LANG="C", LC_ALL="C", LC_MESSAGES="C")
    )
    return dict(cmd=cmd, rc=rc, out=out, err=err)


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def unarchive(self):
    cmd = [self.cmd_path, "--extract", "-C", self.b_dest]
    if self.zipflag:
        cmd.append(self.zipflag)
    if self.opts:
        cmd.extend(["--show-transformed-names"] + self.opts)
    if self.file_args["owner"]:
        cmd.append("--owner=" + quote(self.file_args["owner"]))
    if self.file_args["group"]:
        cmd.append("--group=" + quote(self.file_args["group"]))
    if self.module.params["keep_newer"]:
        cmd.append("--keep-newer-files")
    if self.excludes:
        cmd.extend(["--exclude=" + f for f in self.excludes])
    cmd.extend(["-f", self.src])
    rc, out, err = self.module.run_command(
        cmd, cwd=self.b_dest, environ_update=dict(LANG="C", LC_ALL="C", LC_MESSAGES="C")
    )
    return dict(cmd=cmd, rc=rc, out=out, err=err)
# Buggy code
def __init__(self, src, dest, file_args, module):
    super(TarArchive, self).__init__(src, dest, file_args, module)
    # argument to tar
    self.zipflag = ""


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __init__(self, src, b_dest, file_args, module):
    super(TarArchive, self).__init__(src, b_dest, file_args, module)
    # argument to tar
    self.zipflag = ""
# Buggy code
def __init__(self, src, dest, file_args, module):
    super(TarBzipArchive, self).__init__(src, dest, file_args, module)
    self.zipflag = "-j"


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __init__(self, src, b_dest, file_args, module):
    super(TarBzipArchive, self).__init__(src, b_dest, file_args, module)
    self.zipflag = "-j"
# Buggy code
def __init__(self, src, dest, file_args, module):
    super(TarXzArchive, self).__init__(src, dest, file_args, module)
    self.zipflag = "-J"


# Traceback (nUnicodeEncodeError)
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n    spec.loader.exec_module(module)\r\n  File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n  File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n  File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n    st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __init__(self, src, b_dest, file_args, module):
    super(TarXzArchive, self).__init__(src, b_dest, file_args, module)
    self.zipflag = "-J"
# Buggy code
def delete_metric_alarm(connection, module):
    name = module.params.get("name")

    alarms = connection.describe_alarms(alarm_names=[name])

    if alarms:
        try:
            connection.delete_alarms([name])
            module.exit_json(changed=True)
        except BotoServerError as e:
            module.fail_json(msg=str(e))
    else:
        module.exit_json(changed=False)


# Traceback (nboto.exception.BotoServerError)
2019-04-26 00:11:00,046 p=50 u=root |  fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_y5VU_q/ansible_module_ec2_metric_alarm.py\", line 327, in <module>\n    main()\n  File \"/tmp/ansible_y5VU_q/ansible_module_ec2_metric_alarm.py\", line 320, in main\n    delete_metric_alarm(connection, module)\n  File \"/tmp/ansible_y5VU_q/ansible_module_ec2_metric_alarm.py\", line 263, in delete_metric_alarm\n    alarms = connection.describe_alarms(alarm_names=[name])\n  File \"/usr/local/lib/python2.7/site-packages/boto/ec2/cloudwatch/__init__.py\", line 382, in describe_alarms\n    [('MetricAlarms', MetricAlarms)])\n  File \"/usr/local/lib/python2.7/site-packages/boto/connection.py\", line 1186, in get_list\n    raise self.ResponseError(response.status, response.reason, body)\nboto.exception.BotoServerError: BotoServerError: 400 Bad Request\n<ErrorResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <Error>\n    <Type>Sender</Type>\n    <Code>Throttling</Code>\n    <Message>Rate exceeded</Message>\n  </Error>\n  <RequestId>c5661b3a-67b7-11e9-aeaa-6fd6e091195a</RequestId>\n</ErrorResponse>\n\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def delete_metric_alarm(connection, module):
    name = module.params.get("name")

    alarms = None
    try:
        alarms = connection.describe_alarms(alarm_names=[name])
    except BotoServerError as e:
        module.fail_json(
            msg="Failed to describe alarm %s: %s" % (name, str(e)),
            exception=traceback.format_exc(),
        )

    if alarms:
        try:
            connection.delete_alarms([name])
            module.exit_json(changed=True)
        except BotoServerError as e:
            module.fail_json(msg=str(e))
    else:
        module.exit_json(changed=False)
# Buggy code
def get_config(module, source, filter, lock=False):
    conn = get_connection(module)
    try:
        locked = False
        if lock:
            conn.lock(target=source)
            locked = True
        response = conn.get_config(source=source, filter=filter)

    except ConnectionError as e:
        module.fail_json(msg=to_text(e, errors="surrogate_then_replace").strip())

    finally:
        if locked:
            conn.unlock(target=source)

    return response


# Traceback (TypeError)
TASK [switch : save config] ************************************************************************************************************************************
task path: /home/XXX/roles/switch/tasks/main.yml:29
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: get_config() takes at least 3 arguments (3 given)
fatal: [switch01]: FAILED! => changed=false
module_stderr: |-
Traceback (most recent call last):
File "/home/XXX/.ansible/tmp/ansible-local-68072FPzspT/ansible-tmp-1556809036.71-228316506197860/AnsiballZ_netconf_config.py", line 114, in <module>
_ansiballz_main()
File "/home/XXX/.ansible/tmp/ansible-local-68072FPzspT/ansible-tmp-1556809036.71-228316506197860/AnsiballZ_netconf_config.py", line 106, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/XXX/.ansible/tmp/ansible-local-68072FPzspT/ansible-tmp-1556809036.71-228316506197860/AnsiballZ_netconf_config.py", line 49, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_netconf_config_payload_VY5Wfu/__main__.py", line 439, in <module>
File "/tmp/ansible_netconf_config_payload_VY5Wfu/__main__.py", line 367, in main
TypeError: get_config() takes at least 3 arguments (3 given)
module_stdout: ''
msg: |-
MODULE FAILURE
See stdout/stderr for the exact error
rc: 1

# Fixed code
def get_config(module, source, filter=None, lock=False):
    conn = get_connection(module)
    try:
        locked = False
        if lock:
            conn.lock(target=source)
            locked = True
        response = conn.get_config(source=source, filter=filter)

    except ConnectionError as e:
        module.fail_json(msg=to_text(e, errors="surrogate_then_replace").strip())

    finally:
        if locked:
            conn.unlock(target=source)

    return response
# Buggy code
def detect_build_cache_from(client):
    return client.params["build"] and client.params["build"]["cache_from"] is not None


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 262, in <module>
_ansiballz_main()
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 252, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 120, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 929, in <module>
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 893, in main
KeyError: 'pull'

# Fixed code
def detect_build_cache_from(client):
    return (
        client.module.params["build"]
        and client.module.params["build"].get("cache_from") is not None
    )
# Buggy code
def detect_build_network(client):
    return client.params["build"] and client.params["build"]["network"] is not None


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 262, in <module>
_ansiballz_main()
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 252, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 120, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 929, in <module>
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 893, in main
KeyError: 'pull'

# Fixed code
def detect_build_network(client):
    return (
        client.module.params["build"]
        and client.module.params["build"].get("network") is not None
    )
# Buggy code
def detect_use_config_proxy(client):
    return (
        client.params["build"]
        and client.params["build"]["use_config_proxy"] is not None
    )


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 262, in <module>
_ansiballz_main()
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 252, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/home/debian/.ansible/tmp/ansible-tmp-1554194350.93-186817544577298/AnsiballZ_docker_image.py", line 120, in invoke_module
imp.load_module('__main__', mod, module, MOD_DESC)
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 929, in <module>
File "/tmp/ansible_docker_image_payload_Op5r9S/__main__.py", line 893, in main
KeyError: 'pull'

# Fixed code
def detect_use_config_proxy(client):
    return (
        client.module.params["build"]
        and client.module.params["build"].get("use_config_proxy") is not None
    )
# Buggy code
def __init__(self, client, results):
    super(SwarmManager, self).__init__()

    self.client = client
    self.results = results
    self.check_mode = self.client.check_mode
    self.swarm_info = {}

    self.parameters = TaskParameters(client)


# Traceback (nKeyError)
fatal: [node-01]: FAILED! => {"changed": false, "module_stderr": "Shared connection to node-01 closed.\r\n", "module_stdout": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.24.1) or chardet (2.2.1) doesn't match a supported version!\r\n  RequestsDependencyWarning)\r\nTraceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 113, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 105, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1548156057.5468266-261250085584743/AnsiballZ_docker_swarm.py\", line 48, in invoke_module\r\n    imp.load_module('__main__', mod, module, MOD_DESC)\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 535, in <module>\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 530, in main\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 310, in __call__\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 333, in init_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 390, in __update_swarm\r\n  File \"/tmp/ansible_docker_swarm_payload_2QlvP8/__main__.py\", line 376, in __update_spec\r\nKeyError: 'Labels'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def __init__(self, client, results):
    super(SwarmManager, self).__init__()

    self.client = client
    self.results = results
    self.check_mode = self.client.check_mode
    self.swarm_info = {}

    self.state = client.module.params["state"]
    self.force = client.module.params["force"]

    self.differences = DifferenceTracker()
    self.parameters = TaskParameters.from_ansible_params(client)