"""Statefully manage Vault policies... important:: This module requires the general :ref:`Vault setup <vault-setup>`."""importdifflibimportloggingfromsalt.exceptionsimportCommandExecutionErrorlog=logging.getLogger(__name__)
[docs]defpolicy_present(name,rules):""" Ensure a Vault policy with the given name and rules is present. name The name of the policy rules Rules formatted as in-line HCL .. code-block:: yaml demo-policy: vault.policy_present: - name: foo/bar - rules: | path "secret/top-secret/*" { policy = "deny" } path "secret/not-very-secret/*" { policy = "write" } """ret={"name":name,"changes":{},"result":True,"comment":""}try:existing_rules=__salt__["vault.policy_fetch"](name)exceptCommandExecutionErroraserr:ret["result"]=Falseret["comment"]=f"Failed to read policy: {err}"returnretifexisting_rules==rules:ret["comment"]="Policy exists, and has the correct content"returnretdiff="".join(difflib.unified_diff((existing_rulesor"").splitlines(True),rules.splitlines(True)))ret["changes"]={name:diff}if__opts__["test"]:ret["result"]=Noneret["comment"]="Policy would be "+("created"ifexisting_rulesisNoneelse"updated")returnrettry:__salt__["vault.policy_write"](name,rules)ret["comment"]="Policy has been "+("created"ifexisting_rulesisNoneelse"updated")returnretexceptCommandExecutionErroraserr:return{"name":name,"changes":{},"result":False,"comment":f"Failed to write policy: {err}",}
[docs]defpolicy_absent(name):""" Ensure a Vault policy with the given name and rules is absent. name The name of the policy """ret={"name":name,"changes":{},"result":True,"comment":""}try:existing_rules=__salt__["vault.policy_fetch"](name)exceptCommandExecutionErroraserr:ret["result"]=Falseret["comment"]=f"Failed to read policy: {err}"returnretifexisting_rulesisNone:ret["comment"]="Policy is already absent"returnretret["changes"]={"deleted":name}if__opts__["test"]:ret["result"]=Noneret["comment"]="Policy would be deleted"returnrettry:ifnot__salt__["vault.policy_delete"](name):raiseCommandExecutionError("Policy was initially reported as existent, but seemed to be ""absent while deleting.")ret["comment"]="Policy has been deleted"returnretexceptCommandExecutionErroraserr:return{"name":name,"changes":{},"result":False,"comment":f"Failed to delete policy: {err}",}