Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update hvac error handling (Open todo) #391

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
9646de2
Clean up old import that did not raise an exception when hvac was not…
mathijswesterhof Jul 19, 2023
1b45d32
Check HVAC error and try to gracefully shutdown
mathijswesterhof Jul 19, 2023
cccd86c
Removing traceback and editing exception message; using the original …
mathijswesterhof Jul 20, 2023
77fa4e1
adding self.hvac import to make hvac available to other modules
mathijswesterhof Jul 22, 2023
276c1ad
Merge branch 'main' into pr/mathijswesterhof/391
briantist Dec 26, 2023
5ba39dd
sanity
briantist Dec 26, 2023
78f810b
restore code accidentally removed in merge conflict resolution
briantist Dec 26, 2023
80fb6dc
Merge branch 'main' into pr/mathijswesterhof/391
briantist Dec 26, 2023
731da06
Merge branch 'ansible-collections:main' into mw/update_hvac_error_han…
mathijswesterhof Mar 13, 2024
8d09b15
space common code properly
Mar 17, 2024
2dc4df7
write base, failure and success test for importing the error class
Mar 17, 2024
723cc15
Remove try catch block on vault helper test since it should always su…
Mar 24, 2024
60848af
Merge branch 'ansible-collections:main' into mw/update_hvac_error_han…
mathijswesterhof Jun 15, 2024
d9a6a17
move over to the new HVAC error system for KV modules
mathijswesterhof Jun 15, 2024
b8e3f66
move over to the new HVAC error system for KV modules
mathijswesterhof Jun 15, 2024
16503e7
remove unused imports
mathijswesterhof Jun 15, 2024
06e37f3
create a dedicated function to return the exceptions from HVAC (bette…
mathijswesterhof Jun 15, 2024
629d708
Implement new HVAC error system in all non-database modules
mathijswesterhof Jun 15, 2024
7128a20
removed a little too much, reworked the DEFAULT_MOUNT_POINT variable
mathijswesterhof Jun 18, 2024
35abd1e
return get_hvac_exceptions back to get_hvac().exceptions
mathijswesterhof Jul 28, 2024
9b4b3ab
implement get_hvac().exceptions to all other plugins
mathijswesterhof Jul 28, 2024
e945703
removed HVAC_IMPORT_ERROR from the lookup vault write and adjusted th…
mathijswesterhof Oct 1, 2024
a1d8c74
removed HVAC_IMPORT_ERROR from the last few lookup functions
mathijswesterhof Oct 4, 2024
612a0c3
extended the pki test to include authentication exception
mathijswesterhof Oct 4, 2024
17bb721
Create tests for HashiVaultModule
mathijswesterhof Oct 4, 2024
38e18f0
validate has an exception and is before authenticate so authenticate …
mathijswesterhof Oct 4, 2024
9339e85
Merge branch 'ansible-collections:main' into mw/update_hvac_error_han…
mathijswesterhof Oct 9, 2024
565e687
Merge branch 'ansible-collections:main' into mw/update_hvac_error_han…
mathijswesterhof Oct 9, 2024
021d281
Update plugins/module_utils/_hashi_vault_module.py
briantist Oct 22, 2024
c624634
Update plugins/module_utils/_hashi_vault_module.py
briantist Oct 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions plugins/lookup/hashi_vault.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,18 +244,9 @@

display = Display()

HAS_HVAC = False
try:
import hvac
HAS_HVAC = True
except ImportError:
HAS_HVAC = False


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if not HAS_HVAC:
raise AnsibleError("Please pip install hvac to use the hashi_vault lookup module.")

ret = []

Expand Down Expand Up @@ -314,10 +305,11 @@ def get(self):
field = self._secret_field
secret = self.get_option('secret')
return_as = self.get_option('return_format')
hvac_exceptions = self.helper.get_hvac().exceptions

try:
data = self.client.read(secret)
except hvac.exceptions.Forbidden:
except hvac_exceptions.Forbidden:
raise AnsibleError("Forbidden: Permission Denied to secret '%s'." % secret)

if data is None:
Expand Down
18 changes: 3 additions & 15 deletions plugins/lookup/vault_kv1_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,22 +165,9 @@

display = Display()

try:
import hvac
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

ret = []

self.set_options(direct=kwargs, var_options=variables)
Expand All @@ -190,6 +177,7 @@ def run(self, terms, variables=None, **kwargs):
self.connection_options.process_connection_options()
client_args = self.connection_options.get_hvac_connection_options()
client = self.helper.get_vault_client(**client_args)
hvac_exceptions = self.helper.get_hvac().exceptions

engine_mount_point = self._options_adapter.get_option('engine_mount_point')

Expand All @@ -202,9 +190,9 @@ def run(self, terms, variables=None, **kwargs):
for term in terms:
try:
raw = client.secrets.kv.v1.read_secret(path=term, mount_point=engine_mount_point)
except hvac.exceptions.Forbidden as e:
except hvac_exceptions.Forbidden as e:
raise_from(AnsibleError("Forbidden: Permission Denied to path ['%s']." % term), e)
except hvac.exceptions.InvalidPath as e:
except hvac_exceptions.InvalidPath as e:
if 'Invalid path for a versioned K/V secrets engine' in str(e):
msg = "Invalid path for a versioned K/V secrets engine ['%s']. If this is a KV version 2 path, use community.hashi_vault.vault_kv2_get."
else:
Expand Down
18 changes: 3 additions & 15 deletions plugins/lookup/vault_kv2_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,22 +178,9 @@

display = Display()

try:
import hvac
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

ret = []

self.set_options(direct=kwargs, var_options=variables)
Expand All @@ -203,6 +190,7 @@ def run(self, terms, variables=None, **kwargs):
self.connection_options.process_connection_options()
client_args = self.connection_options.get_hvac_connection_options()
client = self.helper.get_vault_client(**client_args)
hvac_exceptions = self.helper.get_hvac().exceptions

version = self._options_adapter.get_option_default('version')
engine_mount_point = self._options_adapter.get_option('engine_mount_point')
Expand All @@ -216,9 +204,9 @@ def run(self, terms, variables=None, **kwargs):
for term in terms:
try:
raw = client.secrets.kv.v2.read_secret_version(path=term, version=version, mount_point=engine_mount_point)
except hvac.exceptions.Forbidden as e:
except hvac_exceptions.Forbidden as e:
raise_from(AnsibleError("Forbidden: Permission Denied to path ['%s']." % term), e)
except hvac.exceptions.InvalidPath as e:
except hvac_exceptions.InvalidPath as e:
raise_from(
AnsibleError("Invalid or missing path ['%s'] with secret version '%s'. Check the path or secret version." % (term, version or 'latest')),
e
Expand Down
18 changes: 2 additions & 16 deletions plugins/lookup/vault_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,29 +130,14 @@
from ansible.errors import AnsibleError
from ansible.utils.display import Display

from ansible.module_utils.six import raise_from

from ansible_collections.community.hashi_vault.plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase
from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import HashiVaultValueError

display = Display()

try:
import hvac
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

ret = []

self.set_options(direct=kwargs, var_options=variables)
Expand All @@ -162,6 +147,7 @@ def run(self, terms, variables=None, **kwargs):
self.connection_options.process_connection_options()
client_args = self.connection_options.get_hvac_connection_options()
client = self.helper.get_vault_client(**client_args)
hvac_exceptions = self.helper.get_hvac().exceptions

try:
self.authenticator.validate()
Expand All @@ -172,7 +158,7 @@ def run(self, terms, variables=None, **kwargs):
for term in terms:
try:
data = client.list(term)
except hvac.exceptions.Forbidden:
except hvac_exceptions.Forbidden:
raise AnsibleError("Forbidden: Permission Denied to path '%s'." % term)

if data is None:
Expand Down
15 changes: 0 additions & 15 deletions plugins/lookup/vault_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,29 +92,14 @@
from ansible.errors import AnsibleError
from ansible.utils.display import Display

from ansible.module_utils.six import raise_from

from ...plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase
from ...plugins.module_utils._hashi_vault_common import HashiVaultValueError

display = Display()

try:
import hvac # pylint: disable=unused-import
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

self.set_options(direct=kwargs, var_options=variables)
# TODO: remove process_deprecations() if backported fix is available (see method definition)
self.process_deprecations()
Expand Down
18 changes: 2 additions & 16 deletions plugins/lookup/vault_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,29 +84,14 @@
from ansible.errors import AnsibleError
from ansible.utils.display import Display

from ansible.module_utils.six import raise_from

from ansible_collections.community.hashi_vault.plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase
from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import HashiVaultValueError

display = Display()

try:
import hvac
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

ret = []

self.set_options(direct=kwargs, var_options=variables)
Expand All @@ -116,6 +101,7 @@ def run(self, terms, variables=None, **kwargs):
self.connection_options.process_connection_options()
client_args = self.connection_options.get_hvac_connection_options()
client = self.helper.get_vault_client(**client_args)
hvac_exceptions = self.helper.get_hvac().exceptions

try:
self.authenticator.validate()
Expand All @@ -126,7 +112,7 @@ def run(self, terms, variables=None, **kwargs):
for term in terms:
try:
data = client.read(term)
except hvac.exceptions.Forbidden:
except hvac_exceptions.Forbidden:
raise AnsibleError("Forbidden: Permission Denied to path '%s'." % term)

if data is None:
Expand Down
15 changes: 0 additions & 15 deletions plugins/lookup/vault_token_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,11 @@
from ansible.errors import AnsibleError
from ansible.utils.display import Display

from ansible.module_utils.six import raise_from

from ...plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase
from ...plugins.module_utils._hashi_vault_common import HashiVaultValueError

display = Display()

try:
import hvac # pylint: disable=unused-import
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
PASS_THRU_OPTION_NAMES = [
Expand Down Expand Up @@ -141,12 +132,6 @@ class LookupModule(HashiVaultLookupBase):
}

def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

self.set_options(direct=kwargs, var_options=variables)
# TODO: remove process_deprecations() if backported fix is available (see method definition)
self.process_deprecations()
Expand Down
20 changes: 4 additions & 16 deletions plugins/lookup/vault_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,22 +129,9 @@

display = Display()

try:
import hvac
except ImportError as imp_exc:
HVAC_IMPORT_ERROR = imp_exc
else:
HVAC_IMPORT_ERROR = None


class LookupModule(HashiVaultLookupBase):
def run(self, terms, variables=None, **kwargs):
if HVAC_IMPORT_ERROR:
raise_from(
AnsibleError("This plugin requires the 'hvac' Python library"),
HVAC_IMPORT_ERROR
)

ret = []

self.set_options(direct=kwargs, var_options=variables)
Expand All @@ -154,6 +141,7 @@
self.connection_options.process_connection_options()
client_args = self.connection_options.get_hvac_connection_options()
client = self.helper.get_vault_client(**client_args)
hvac_exceptions = self.helper.get_hvac().exceptions

data = self._options_adapter.get_option('data')
wrap_ttl = self._options_adapter.get_option_default('wrap_ttl')
Expand All @@ -176,11 +164,11 @@
raise_from(AnsibleError("To use 'path' or 'wrap_ttl' as data keys, use hvac >= 1.2"), e)
else:
response = client.write(path=term, wrap_ttl=wrap_ttl, **data)
except hvac.exceptions.Forbidden as e:
except hvac_exceptions.Forbidden as e:
raise_from(AnsibleError("Forbidden: Permission Denied to path '%s'." % term), e)
except hvac.exceptions.InvalidPath as e:
except hvac_exceptions.InvalidPath as e:
raise_from(AnsibleError("The path '%s' doesn't seem to exist." % term), e)
except hvac.exceptions.InternalServerError as e:
except hvac_exceptions.InternalServerError as e:

Check warning on line 171 in plugins/lookup/vault_write.py

View check run for this annotation

Codecov / codecov/patch

plugins/lookup/vault_write.py#L171

Added line #L171 was not covered by tests
raise_from(AnsibleError("Internal Server Error: %s" % str(e)), e)

# https://github.com/hvac/hvac/issues/797
Expand Down
29 changes: 18 additions & 11 deletions plugins/module_utils/_hashi_vault_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,29 @@
import os


HAS_HVAC = False
try:
import hvac
HAS_HVAC = True
except ImportError:
HAS_HVAC = False


class HashiVaultValueError(ValueError):
'''Use in common code to raise an Exception that can be turned into AnsibleError or used to fail_json()'''


class HashiVaultHVACError(ImportError):
'''Use in common code to signal HVAC is missing.'''
def __init__(self, error, msg):
super().__init__(error)
self.msg = msg
self.error = error

Check warning on line 29 in plugins/module_utils/_hashi_vault_common.py

View check run for this annotation

Codecov / codecov/patch

plugins/module_utils/_hashi_vault_common.py#L27-L29

Added lines #L27 - L29 were not covered by tests


class HashiVaultHelper():
def __init__(self):
# TODO move hvac checking here?
pass
try:
import hvac
self.hvac = hvac
except ImportError as e:
from ansible.module_utils.basic import missing_required_lib
raise HashiVaultHVACError(error=str(e), msg=missing_required_lib('hvac'))

Check warning on line 39 in plugins/module_utils/_hashi_vault_common.py

View check run for this annotation

Codecov / codecov/patch

plugins/module_utils/_hashi_vault_common.py#L37-L39

Added lines #L37 - L39 were not covered by tests

def get_hvac(self):
return self.hvac

def get_vault_client(
self,
Expand All @@ -50,7 +57,7 @@
:type hashi_vault_revoke_on_logout: bool
'''

client = hvac.Client(**kwargs)
client = self.hvac.Client(**kwargs)

# logout to prevent accidental use of inferred tokens
# https://github.com/ansible-collections/community.hashi_vault/issues/13
Expand Down
10 changes: 9 additions & 1 deletion plugins/module_utils/_hashi_vault_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import (
HashiVaultHelper,
HashiVaultHVACError,
HashiVaultOptionAdapter,
)
from ansible_collections.community.hashi_vault.plugins.module_utils._connection_options import HashiVaultConnectionOptions
Expand All @@ -31,7 +32,14 @@

super(HashiVaultModule, self).__init__(*args, **kwargs)

self.helper = HashiVaultHelper()
try:
self.helper = HashiVaultHelper()
except HashiVaultHVACError as exc:
self.fail_json(

Check warning on line 38 in plugins/module_utils/_hashi_vault_module.py

View check run for this annotation

Codecov / codecov/patch

plugins/module_utils/_hashi_vault_module.py#L37-L38

Added lines #L37 - L38 were not covered by tests
msg=exc.msg,
exception=exc.error
)

self.adapter = HashiVaultOptionAdapter.from_dict(self.params)
self.connection_options = HashiVaultConnectionOptions(option_adapter=self.adapter, retry_callback_generator=callback)
self.authenticator = HashiVaultAuthenticator(option_adapter=self.adapter, warning_callback=self.warn, deprecate_callback=self.deprecate)
Expand Down
Loading
Loading