# Buggy code
def _find_module_utils(
    module_name,
    b_module_data,
    module_path,
    module_args,
    task_vars,
    templar,
    module_compression,
    async_timeout,
    become,
    become_method,
    become_user,
    become_password,
    become_flags,
    environment,
):
    """
    Given the source of the module, convert it to a Jinja2 template to insert
    module code and return whether it's a new or old style module.
    """
    module_substyle = module_style = "old"

    # module_style is something important to calling code (ActionBase).  It
    # determines how arguments are formatted (json vs k=v) and whether
    # a separate arguments file needs to be sent over the wire.
    # module_substyle is extra information that's useful internally.  It tells
    # us what we have to look to substitute in the module files and whether
    # we're using module replacer or ansiballz to format the module itself.
    if _is_binary(b_module_data):
        module_substyle = module_style = "binary"
    elif REPLACER in b_module_data:
        # Do REPLACER before from ansible.module_utils because we need make sure
        # we substitute "from ansible.module_utils basic" for REPLACER
        module_style = "new"
        module_substyle = "python"
        b_module_data = b_module_data.replace(
            REPLACER, b"from ansible.module_utils.basic import *"
        )
    elif b"from ansible.module_utils." in b_module_data:
        module_style = "new"
        module_substyle = "python"
    elif REPLACER_WINDOWS in b_module_data:
        module_style = "new"
        module_substyle = "powershell"
        b_module_data = b_module_data.replace(
            REPLACER_WINDOWS, b"#Requires -Module Ansible.ModuleUtils.Legacy"
        )
    elif (
        re.search(b"#Requires -Module", b_module_data, re.IGNORECASE)
        or re.search(b"#Requires -Version", b_module_data, re.IGNORECASE)
        or re.search(b"#AnsibleRequires -OSVersion", b_module_data, re.IGNORECASE)
        or re.search(b"#AnsibleRequires -CSharpUtil", b_module_data, re.IGNORECASE)
    ):
        module_style = "new"
        module_substyle = "powershell"
    elif REPLACER_JSONARGS in b_module_data:
        module_style = "new"
        module_substyle = "jsonargs"
    elif b"WANT_JSON" in b_module_data:
        module_substyle = module_style = "non_native_want_json"

    shebang = None
    # Neither old-style, non_native_want_json nor binary modules should be modified
    # except for the shebang line (Done by modify_module)
    if module_style in ("old", "non_native_want_json", "binary"):
        return b_module_data, module_style, shebang

    output = BytesIO()
    py_module_names = set()

    if module_substyle == "python":
        params = dict(
            ANSIBLE_MODULE_ARGS=module_args,
        )
        python_repred_params = repr(json.dumps(params))

        try:
            compression_method = getattr(zipfile, module_compression)
        except AttributeError:
            display.warning(
                "Bad module compression string specified: %s.  Using ZIP_STORED (no compression)"
                % module_compression
            )
            compression_method = zipfile.ZIP_STORED

        lookup_path = os.path.join(C.DEFAULT_LOCAL_TMP, "ansiballz_cache")
        cached_module_filename = os.path.join(
            lookup_path, "%s-%s" % (module_name, module_compression)
        )

        zipdata = None
        # Optimization -- don't lock if the module has already been cached
        if os.path.exists(cached_module_filename):
            display.debug("ANSIBALLZ: using cached module: %s" % cached_module_filename)
            with open(cached_module_filename, "rb") as module_data:
                zipdata = module_data.read()
        else:
            if module_name in action_write_locks.action_write_locks:
                display.debug("ANSIBALLZ: Using lock for %s" % module_name)
                lock = action_write_locks.action_write_locks[module_name]
            else:
                # If the action plugin directly invokes the module (instead of
                # going through a strategy) then we don't have a cross-process
                # Lock specifically for this module.  Use the "unexpected
                # module" lock instead
                display.debug("ANSIBALLZ: Using generic lock for %s" % module_name)
                lock = action_write_locks.action_write_locks[None]

            display.debug("ANSIBALLZ: Acquiring lock")
            with lock:
                display.debug("ANSIBALLZ: Lock acquired: %s" % id(lock))
                # Check that no other process has created this while we were
                # waiting for the lock
                if not os.path.exists(cached_module_filename):
                    display.debug("ANSIBALLZ: Creating module")
                    # Create the module zip data
                    zipoutput = BytesIO()
                    zf = zipfile.ZipFile(
                        zipoutput, mode="w", compression=compression_method
                    )
                    # Note: If we need to import from release.py first,
                    # remember to catch all exceptions: https://github.com/ansible/ansible/issues/16523
                    zf.writestr(
                        "ansible/__init__.py",
                        b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n__version__="'
                        + to_bytes(__version__)
                        + b'"\n__author__="'
                        + to_bytes(__author__)
                        + b'"\n',
                    )
                    zf.writestr(
                        "ansible/module_utils/__init__.py",
                        b"from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n",
                    )

                    zf.writestr("__main__.py", b_module_data)

                    py_module_cache = {("__init__",): (b"", "[builtin]")}
                    recursive_finder(
                        module_name, b_module_data, py_module_names, py_module_cache, zf
                    )
                    zf.close()
                    zipdata = base64.b64encode(zipoutput.getvalue())

                    # Write the assembled module to a temp file (write to temp
                    # so that no one looking for the file reads a partially
                    # written file)
                    if not os.path.exists(lookup_path):
                        # Note -- if we have a global function to setup, that would
                        # be a better place to run this
                        os.makedirs(lookup_path)
                    display.debug("ANSIBALLZ: Writing module")
                    with open(cached_module_filename + "-part", "wb") as f:
                        f.write(zipdata)

                    # Rename the file into its final position in the cache so
                    # future users of this module can read it off the
                    # filesystem instead of constructing from scratch.
                    display.debug("ANSIBALLZ: Renaming module")
                    os.rename(cached_module_filename + "-part", cached_module_filename)
                    display.debug("ANSIBALLZ: Done creating module")

            if zipdata is None:
                display.debug("ANSIBALLZ: Reading module after lock")
                # Another process wrote the file while we were waiting for
                # the write lock.  Go ahead and read the data from disk
                # instead of re-creating it.
                try:
                    with open(cached_module_filename, "rb") as f:
                        zipdata = f.read()
                except IOError:
                    raise AnsibleError(
                        "A different worker process failed to create module file. "
                        "Look at traceback for that process for debugging information."
                    )
        zipdata = to_text(zipdata, errors="surrogate_or_strict")

        shebang, interpreter = _get_shebang("/usr/bin/python", task_vars, templar)
        if shebang is None:
            shebang = "#!/usr/bin/python"

        # Enclose the parts of the interpreter in quotes because we're
        # substituting it into the template as a Python string
        interpreter_parts = interpreter.split(" ")
        interpreter = "'{0}'".format("', '".join(interpreter_parts))

        # FUTURE: the module cache entry should be invalidated if we got this value from a host-dependent source
        rlimit_nofile = C.config.get_config_value(
            "PYTHON_MODULE_RLIMIT_NOFILE", variables=task_vars
        )

        if not isinstance(rlimit_nofile, int):
            rlimit_nofile = int(templar.template(rlimit_nofile))

        if rlimit_nofile:
            rlimit = ANSIBALLZ_RLIMIT_TEMPLATE % dict(
                rlimit_nofile=rlimit_nofile,
            )
        else:
            rlimit = ""

        coverage_config = os.environ.get("_ANSIBLE_COVERAGE_CONFIG")

        if coverage_config:
            # Enable code coverage analysis of the module.
            # This feature is for internal testing and may change without notice.
            coverage = ANSIBALLZ_COVERAGE_TEMPLATE % dict(
                coverage_config=coverage_config,
                coverage_output=os.environ["_ANSIBLE_COVERAGE_OUTPUT"],
            )
        else:
            coverage = ""

        now = datetime.datetime.utcnow()
        output.write(
            to_bytes(
                ACTIVE_ANSIBALLZ_TEMPLATE
                % dict(
                    zipdata=zipdata,
                    ansible_module=module_name,
                    params=python_repred_params,
                    shebang=shebang,
                    interpreter=interpreter,
                    coding=ENCODING_STRING,
                    year=now.year,
                    month=now.month,
                    day=now.day,
                    hour=now.hour,
                    minute=now.minute,
                    second=now.second,
                    coverage=coverage,
                    rlimit=rlimit,
                )
            )
        )
        b_module_data = output.getvalue()

    elif module_substyle == "powershell":
        # Powershell/winrm don't actually make use of shebang so we can
        # safely set this here.  If we let the fallback code handle this
        # it can fail in the presence of the UTF8 BOM commonly added by
        # Windows text editors
        shebang = "#!powershell"
        # create the common exec wrapper payload and set that as the module_data
        # bytes
        b_module_data = ps_manifest._create_powershell_wrapper(
            b_module_data,
            module_args,
            environment,
            async_timeout,
            become,
            become_method,
            become_user,
            become_password,
            become_flags,
            module_substyle,
        )

    elif module_substyle == "jsonargs":
        module_args_json = to_bytes(json.dumps(module_args))

        # these strings could be included in a third-party module but
        # officially they were included in the 'basic' snippet for new-style
        # python modules (which has been replaced with something else in
        # ansiballz) If we remove them from jsonargs-style module replacer
        # then we can remove them everywhere.
        python_repred_args = to_bytes(repr(module_args_json))
        b_module_data = b_module_data.replace(
            REPLACER_VERSION, to_bytes(repr(__version__))
        )
        b_module_data = b_module_data.replace(REPLACER_COMPLEX, python_repred_args)
        b_module_data = b_module_data.replace(
            REPLACER_SELINUX, to_bytes(",".join(C.DEFAULT_SELINUX_SPECIAL_FS))
        )

        # The main event -- substitute the JSON args string into the module
        b_module_data = b_module_data.replace(REPLACER_JSONARGS, module_args_json)

        facility = b"syslog." + to_bytes(
            task_vars.get("ansible_syslog_facility", C.DEFAULT_SYSLOG_FACILITY),
            errors="surrogate_or_strict",
        )
        b_module_data = b_module_data.replace(b"syslog.LOG_USER", facility)

    return (b_module_data, module_style, shebang)


# Traceback (TypeError)
TASK [Subscribe to Red Hat] ***************************************************************************
task path: /home/itengval/vagrant/rhel-single/prepare_rhel.yml:6
Trying secret FileVaultSecret(filename='/home/itengval/vagrant/rhel-single/.vault-password') for vault_id=default
<192.168.121.21> ESTABLISH SSH CONNECTION FOR USER: vagrant
<192.168.121.21> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o Port=22 -o 'IdentityFile="/home/itengval/vagrant/rhel-single/.vagrant/machines/rhel-test/libvirt/private_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=vagrant -o ConnectTimeout=10 -o ControlPath=/home/itengval/.ansible/cp/0be10b0f42 192.168.121.21 '/bin/sh -c '"'"'echo ~vagrant &amp;&amp; sleep 0'"'"''
<192.168.121.21> (0, '/home/vagrant\n', 'OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017\r\ndebug1: Reading configuration data /home/itengval/.ssh/config\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 58: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 4 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 3885\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 0\r\n')
<192.168.121.21> ESTABLISH SSH CONNECTION FOR USER: vagrant
<192.168.121.21> SSH: EXEC ssh -vvv -C -o ControlMaster=auto -o ControlPersist=60s -o Port=22 -o 'IdentityFile="/home/itengval/vagrant/rhel-single/.vagrant/machines/rhel-test/libvirt/private_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=vagrant -o ConnectTimeout=10 -o ControlPath=/home/itengval/.ansible/cp/0be10b0f42 192.168.121.21 '/bin/sh -c '"'"'( umask 77 &amp;&amp; mkdir -p "` echo /home/vagrant/.ansible/tmp/ansible-tmp-1550733575.47-199078368267259 `" &amp;&amp; echo ansible-tmp-1550733575.47-199078368267259="` echo /home/vagrant/.ansible/tmp/ansible-tmp-1550733575.47-199078368267259 `" ) &amp;&amp; sleep 0'"'"''
<192.168.121.21> (0, 'ansible-tmp-1550733575.47-199078368267259=/home/vagrant/.ansible/tmp/ansible-tmp-1550733575.47-199078368267259\n', 'OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017\r\ndebug1: Reading configuration data /home/itengval/.ssh/config\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 58: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 4 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 3885\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 0\r\n')
Trying secret FileVaultSecret(filename='/home/itengval/vagrant/rhel-single/.vault-password') for vault_id=default
The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 140, in run
res = self._execute()
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 612, in _execute
result = self._handler.run(task_vars=variables)
File "/usr/lib/python2.7/site-packages/ansible/plugins/action/normal.py", line 46, in run
result = merge_hash(result, self._execute_module(task_vars=task_vars, wrap_async=wrap_async))
File "/usr/lib/python2.7/site-packages/ansible/plugins/action/__init__.py", line 739, in _execute_module
(module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
File "/usr/lib/python2.7/site-packages/ansible/plugins/action/__init__.py", line 178, in _configure_module
environment=final_environment)
File "/usr/lib/python2.7/site-packages/ansible/executor/module_common.py", line 973, in modify_module
environment=environment)
File "/usr/lib/python2.7/site-packages/ansible/executor/module_common.py", line 742, in _find_module_utils
python_repred_params = repr(json.dumps(params))
File "/usr/lib64/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib64/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: u'perkele' is not JSON serializable

fatal: [rhel-test]: FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}

# Fixed code
def _find_module_utils(
    module_name,
    b_module_data,
    module_path,
    module_args,
    task_vars,
    templar,
    module_compression,
    async_timeout,
    become,
    become_method,
    become_user,
    become_password,
    become_flags,
    environment,
):
    """
    Given the source of the module, convert it to a Jinja2 template to insert
    module code and return whether it's a new or old style module.
    """
    module_substyle = module_style = "old"

    # module_style is something important to calling code (ActionBase).  It
    # determines how arguments are formatted (json vs k=v) and whether
    # a separate arguments file needs to be sent over the wire.
    # module_substyle is extra information that's useful internally.  It tells
    # us what we have to look to substitute in the module files and whether
    # we're using module replacer or ansiballz to format the module itself.
    if _is_binary(b_module_data):
        module_substyle = module_style = "binary"
    elif REPLACER in b_module_data:
        # Do REPLACER before from ansible.module_utils because we need make sure
        # we substitute "from ansible.module_utils basic" for REPLACER
        module_style = "new"
        module_substyle = "python"
        b_module_data = b_module_data.replace(
            REPLACER, b"from ansible.module_utils.basic import *"
        )
    elif b"from ansible.module_utils." in b_module_data:
        module_style = "new"
        module_substyle = "python"
    elif REPLACER_WINDOWS in b_module_data:
        module_style = "new"
        module_substyle = "powershell"
        b_module_data = b_module_data.replace(
            REPLACER_WINDOWS, b"#Requires -Module Ansible.ModuleUtils.Legacy"
        )
    elif (
        re.search(b"#Requires -Module", b_module_data, re.IGNORECASE)
        or re.search(b"#Requires -Version", b_module_data, re.IGNORECASE)
        or re.search(b"#AnsibleRequires -OSVersion", b_module_data, re.IGNORECASE)
        or re.search(b"#AnsibleRequires -CSharpUtil", b_module_data, re.IGNORECASE)
    ):
        module_style = "new"
        module_substyle = "powershell"
    elif REPLACER_JSONARGS in b_module_data:
        module_style = "new"
        module_substyle = "jsonargs"
    elif b"WANT_JSON" in b_module_data:
        module_substyle = module_style = "non_native_want_json"

    shebang = None
    # Neither old-style, non_native_want_json nor binary modules should be modified
    # except for the shebang line (Done by modify_module)
    if module_style in ("old", "non_native_want_json", "binary"):
        return b_module_data, module_style, shebang

    output = BytesIO()
    py_module_names = set()

    if module_substyle == "python":
        params = dict(
            ANSIBLE_MODULE_ARGS=module_args,
        )
        try:
            python_repred_params = repr(json.dumps(params))
        except TypeError as e:
            raise AnsibleError(
                "Unable to pass options to module, they must be JSON serializable: %s"
                % to_native(e)
            )

        try:
            compression_method = getattr(zipfile, module_compression)
        except AttributeError:
            display.warning(
                "Bad module compression string specified: %s.  Using ZIP_STORED (no compression)"
                % module_compression
            )
            compression_method = zipfile.ZIP_STORED

        lookup_path = os.path.join(C.DEFAULT_LOCAL_TMP, "ansiballz_cache")
        cached_module_filename = os.path.join(
            lookup_path, "%s-%s" % (module_name, module_compression)
        )

        zipdata = None
        # Optimization -- don't lock if the module has already been cached
        if os.path.exists(cached_module_filename):
            display.debug("ANSIBALLZ: using cached module: %s" % cached_module_filename)
            with open(cached_module_filename, "rb") as module_data:
                zipdata = module_data.read()
        else:
            if module_name in action_write_locks.action_write_locks:
                display.debug("ANSIBALLZ: Using lock for %s" % module_name)
                lock = action_write_locks.action_write_locks[module_name]
            else:
                # If the action plugin directly invokes the module (instead of
                # going through a strategy) then we don't have a cross-process
                # Lock specifically for this module.  Use the "unexpected
                # module" lock instead
                display.debug("ANSIBALLZ: Using generic lock for %s" % module_name)
                lock = action_write_locks.action_write_locks[None]

            display.debug("ANSIBALLZ: Acquiring lock")
            with lock:
                display.debug("ANSIBALLZ: Lock acquired: %s" % id(lock))
                # Check that no other process has created this while we were
                # waiting for the lock
                if not os.path.exists(cached_module_filename):
                    display.debug("ANSIBALLZ: Creating module")
                    # Create the module zip data
                    zipoutput = BytesIO()
                    zf = zipfile.ZipFile(
                        zipoutput, mode="w", compression=compression_method
                    )
                    # Note: If we need to import from release.py first,
                    # remember to catch all exceptions: https://github.com/ansible/ansible/issues/16523
                    zf.writestr(
                        "ansible/__init__.py",
                        b'from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n__version__="'
                        + to_bytes(__version__)
                        + b'"\n__author__="'
                        + to_bytes(__author__)
                        + b'"\n',
                    )
                    zf.writestr(
                        "ansible/module_utils/__init__.py",
                        b"from pkgutil import extend_path\n__path__=extend_path(__path__,__name__)\n",
                    )

                    zf.writestr("__main__.py", b_module_data)

                    py_module_cache = {("__init__",): (b"", "[builtin]")}
                    recursive_finder(
                        module_name, b_module_data, py_module_names, py_module_cache, zf
                    )
                    zf.close()
                    zipdata = base64.b64encode(zipoutput.getvalue())

                    # Write the assembled module to a temp file (write to temp
                    # so that no one looking for the file reads a partially
                    # written file)
                    if not os.path.exists(lookup_path):
                        # Note -- if we have a global function to setup, that would
                        # be a better place to run this
                        os.makedirs(lookup_path)
                    display.debug("ANSIBALLZ: Writing module")
                    with open(cached_module_filename + "-part", "wb") as f:
                        f.write(zipdata)

                    # Rename the file into its final position in the cache so
                    # future users of this module can read it off the
                    # filesystem instead of constructing from scratch.
                    display.debug("ANSIBALLZ: Renaming module")
                    os.rename(cached_module_filename + "-part", cached_module_filename)
                    display.debug("ANSIBALLZ: Done creating module")

            if zipdata is None:
                display.debug("ANSIBALLZ: Reading module after lock")
                # Another process wrote the file while we were waiting for
                # the write lock.  Go ahead and read the data from disk
                # instead of re-creating it.
                try:
                    with open(cached_module_filename, "rb") as f:
                        zipdata = f.read()
                except IOError:
                    raise AnsibleError(
                        "A different worker process failed to create module file. "
                        "Look at traceback for that process for debugging information."
                    )
        zipdata = to_text(zipdata, errors="surrogate_or_strict")

        shebang, interpreter = _get_shebang("/usr/bin/python", task_vars, templar)
        if shebang is None:
            shebang = "#!/usr/bin/python"

        # Enclose the parts of the interpreter in quotes because we're
        # substituting it into the template as a Python string
        interpreter_parts = interpreter.split(" ")
        interpreter = "'{0}'".format("', '".join(interpreter_parts))

        # FUTURE: the module cache entry should be invalidated if we got this value from a host-dependent source
        rlimit_nofile = C.config.get_config_value(
            "PYTHON_MODULE_RLIMIT_NOFILE", variables=task_vars
        )

        if not isinstance(rlimit_nofile, int):
            rlimit_nofile = int(templar.template(rlimit_nofile))

        if rlimit_nofile:
            rlimit = ANSIBALLZ_RLIMIT_TEMPLATE % dict(
                rlimit_nofile=rlimit_nofile,
            )
        else:
            rlimit = ""

        coverage_config = os.environ.get("_ANSIBLE_COVERAGE_CONFIG")

        if coverage_config:
            # Enable code coverage analysis of the module.
            # This feature is for internal testing and may change without notice.
            coverage = ANSIBALLZ_COVERAGE_TEMPLATE % dict(
                coverage_config=coverage_config,
                coverage_output=os.environ["_ANSIBLE_COVERAGE_OUTPUT"],
            )
        else:
            coverage = ""

        now = datetime.datetime.utcnow()
        output.write(
            to_bytes(
                ACTIVE_ANSIBALLZ_TEMPLATE
                % dict(
                    zipdata=zipdata,
                    ansible_module=module_name,
                    params=python_repred_params,
                    shebang=shebang,
                    interpreter=interpreter,
                    coding=ENCODING_STRING,
                    year=now.year,
                    month=now.month,
                    day=now.day,
                    hour=now.hour,
                    minute=now.minute,
                    second=now.second,
                    coverage=coverage,
                    rlimit=rlimit,
                )
            )
        )
        b_module_data = output.getvalue()

    elif module_substyle == "powershell":
        # Powershell/winrm don't actually make use of shebang so we can
        # safely set this here.  If we let the fallback code handle this
        # it can fail in the presence of the UTF8 BOM commonly added by
        # Windows text editors
        shebang = "#!powershell"
        # create the common exec wrapper payload and set that as the module_data
        # bytes
        b_module_data = ps_manifest._create_powershell_wrapper(
            b_module_data,
            module_args,
            environment,
            async_timeout,
            become,
            become_method,
            become_user,
            become_password,
            become_flags,
            module_substyle,
        )

    elif module_substyle == "jsonargs":
        module_args_json = to_bytes(json.dumps(module_args))

        # these strings could be included in a third-party module but
        # officially they were included in the 'basic' snippet for new-style
        # python modules (which has been replaced with something else in
        # ansiballz) If we remove them from jsonargs-style module replacer
        # then we can remove them everywhere.
        python_repred_args = to_bytes(repr(module_args_json))
        b_module_data = b_module_data.replace(
            REPLACER_VERSION, to_bytes(repr(__version__))
        )
        b_module_data = b_module_data.replace(REPLACER_COMPLEX, python_repred_args)
        b_module_data = b_module_data.replace(
            REPLACER_SELINUX, to_bytes(",".join(C.DEFAULT_SELINUX_SPECIAL_FS))
        )

        # The main event -- substitute the JSON args string into the module
        b_module_data = b_module_data.replace(REPLACER_JSONARGS, module_args_json)

        facility = b"syslog." + to_bytes(
            task_vars.get("ansible_syslog_facility", C.DEFAULT_SYSLOG_FACILITY),
            errors="surrogate_or_strict",
        )
        b_module_data = b_module_data.replace(b"syslog.LOG_USER", facility)

    return (b_module_data, module_style, shebang)