# Buggy code
def private_key_managed(
    name,
    bits=2048,
    passphrase=None,
    cipher="aes_128_cbc",
    new=False,
    overwrite=False,
    verbose=True,
    **kwargs,
):
    """
    Manage a private key's existence.

    name:
        Path to the private key

    bits:
        Key length in bits. Default 2048.

    passphrase:
        Passphrase for encrypting the private key.

    cipher:
        Cipher for encrypting the private key.

    new:
        Always create a new key. Defaults to ``False``.
        Combining new with :mod:`prereq <salt.states.requsities.preqreq>`, or when used as part of a `managed_private_key` can allow key rotation whenever a new certificate is generated.

    overwrite:
        Overwrite an existing private key if the provided passphrase cannot decrypt it.

    verbose:
        Provide visual feedback on stdout, dots while key is generated.
        Default is True.

        .. versionadded:: 2016.11.0

    kwargs:
        Any kwargs supported by file.managed are supported.

    Example:

    The JINJA templating in this example ensures a private key is generated if the file doesn't exist
    and that a new private key is generated whenever the certificate that uses it is to be renewed.

    .. code-block:: jinja

        /etc/pki/www.key:
          x509.private_key_managed:
            - bits: 4096
            - new: True
            {% if salt['file.file_exists']('/etc/pki/www.key') -%}
            - prereq:
              - x509: /etc/pki/www.crt
            {%- endif %}
    """
    file_args, kwargs = _get_file_args(name, **kwargs)
    new_key = False
    if _check_private_key(
        name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite
    ):
        file_args["contents"] = __salt__["x509.get_pem_entry"](
            name, pem_type="RSA PRIVATE KEY"
        )
    else:
        new_key = True
        file_args["contents"] = __salt__["x509.create_private_key"](
            text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose
        )

    # Ensure the key contents are a string before passing it along
    file_args["contents"] = salt.utils.stringutils.to_str(file_args["contents"])

    ret = __states__["file.managed"](**file_args)
    if ret["changes"] and new_key:
        ret["changes"] = {"new": "New private key generated"}

    return ret


# Traceback (SaltInvocationError)
ID: /etc/nginx/certs/localhost.cert.pem
Function: x509.certificate_managed
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1745, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1702, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/x509.py", line 473, in certificate_managed
new = __salt__['x509.create_certificate'](testrun=True, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 1484, in create_certificate
passphrase=kwargs['signing_private_key_passphrase'])
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 679, in get_public_key
text = get_pem_entry(text)
File "/usr/lib/python2.7/site-packages/salt/modules/x509.py", line 472, in get_pem_entry
raise salt.exceptions.SaltInvocationError(errmsg)
SaltInvocationError: PEM text not valid:
/etc/nginx/private/localhost.key.pem
Started: 16:29:53.585609
Duration: 99.44 ms
Changes:

# Fixed code
def private_key_managed(
    name,
    bits=2048,
    passphrase=None,
    cipher="aes_128_cbc",
    new=False,
    overwrite=False,
    verbose=True,
    **kwargs,
):
    """
    Manage a private key's existence.

    name:
        Path to the private key

    bits:
        Key length in bits. Default 2048.

    passphrase:
        Passphrase for encrypting the private key.

    cipher:
        Cipher for encrypting the private key.

    new:
        Always create a new key. Defaults to ``False``.
        Combining new with :mod:`prereq <salt.states.requsities.preqreq>`
        can allow key rotation whenever a new certificate is generated.

    overwrite:
        Overwrite an existing private key if the provided passphrase cannot decrypt it.

    verbose:
        Provide visual feedback on stdout, dots while key is generated.
        Default is True.

        .. versionadded:: 2016.11.0

    kwargs:
        Any kwargs supported by file.managed are supported.

    Example:

    The JINJA templating in this example ensures a private key is generated if the file doesn't exist
    and that a new private key is generated whenever the certificate that uses it is to be renewed.

    .. code-block:: jinja

        /etc/pki/www.key:
          x509.private_key_managed:
            - bits: 4096
            - new: True
            {% if salt['file.file_exists']('/etc/pki/www.key') -%}
            - prereq:
              - x509: /etc/pki/www.crt
            {%- endif %}
    """
    file_args, kwargs = _get_file_args(name, **kwargs)
    new_key = False
    if _check_private_key(
        name, bits=bits, passphrase=passphrase, new=new, overwrite=overwrite
    ):
        file_args["contents"] = __salt__["x509.get_pem_entry"](
            name, pem_type="RSA PRIVATE KEY"
        )
    else:
        new_key = True
        file_args["contents"] = __salt__["x509.create_private_key"](
            text=True, bits=bits, passphrase=passphrase, cipher=cipher, verbose=verbose
        )

    # Ensure the key contents are a string before passing it along
    file_args["contents"] = salt.utils.stringutils.to_str(file_args["contents"])

    ret = __states__["file.managed"](**file_args)
    if ret["changes"] and new_key:
        ret["changes"] = {"new": "New private key generated"}

    return ret