mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-02-04 07:51:50 +00:00
Use raise from in modules (#11097)
* Use raise from. * Add changelog fragment. * Add comment.
This commit is contained in:
parent
2b4333a033
commit
40aea793ee
21 changed files with 60 additions and 39 deletions
21
changelogs/fragments/11097-raise-from.yml
Normal file
21
changelogs/fragments/11097-raise-from.yml
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
minor_changes:
|
||||||
|
- cmd_runner module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- csv module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- database module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- hwc_utils module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- identity.keycloak.keycloak module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- ipa module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- lxd module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- net_tools.pritunl.api module utils - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- cronvar - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- jenkins_plugin - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- jira - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- layman - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- listen_ports_facts - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- osx_defaults - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- packet_ip_subnet - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- packet_sshkey - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- pids - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- rhevm - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- vertica_schema - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
- vertica_user - use ``raise ... from ...`` when passing on exceptions (https://github.com/ansible-collections/community.general/pull/11097).
|
||||||
|
|
@ -194,7 +194,7 @@ class _CmdRunnerContext:
|
||||||
except MissingArgumentValue:
|
except MissingArgumentValue:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise FormatError(arg_name, value, runner.arg_formats[arg_name], e)
|
raise FormatError(arg_name, value, runner.arg_formats[arg_name], e) from e
|
||||||
|
|
||||||
if self.check_mode_skip and module.check_mode:
|
if self.check_mode_skip and module.check_mode:
|
||||||
return self.check_mode_return
|
return self.check_mode_return
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ def initialize_dialect(dialect, **kwargs):
|
||||||
try:
|
try:
|
||||||
csv.register_dialect("custom", dialect, **dialect_params)
|
csv.register_dialect("custom", dialect, **dialect_params)
|
||||||
except TypeError as e:
|
except TypeError as e:
|
||||||
raise CustomDialectFailureError(f"Unable to create custom dialect: {e}")
|
raise CustomDialectFailureError(f"Unable to create custom dialect: {e}") from e
|
||||||
dialect = "custom"
|
dialect = "custom"
|
||||||
|
|
||||||
return dialect
|
return dialect
|
||||||
|
|
|
||||||
|
|
@ -56,8 +56,8 @@ def _find_end_quote(identifier, quote_char):
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
quote = identifier.index(quote_char)
|
quote = identifier.index(quote_char)
|
||||||
except ValueError:
|
except ValueError as e:
|
||||||
raise UnclosedQuoteError
|
raise UnclosedQuoteError from e
|
||||||
accumulate = accumulate + quote
|
accumulate = accumulate + quote
|
||||||
try:
|
try:
|
||||||
next_char = identifier[quote + 1]
|
next_char = identifier[quote + 1]
|
||||||
|
|
@ -67,8 +67,8 @@ def _find_end_quote(identifier, quote_char):
|
||||||
try:
|
try:
|
||||||
identifier = identifier[quote + 2 :]
|
identifier = identifier[quote + 2 :]
|
||||||
accumulate = accumulate + 2
|
accumulate = accumulate + 2
|
||||||
except IndexError:
|
except IndexError as e:
|
||||||
raise UnclosedQuoteError
|
raise UnclosedQuoteError from e
|
||||||
else:
|
else:
|
||||||
return accumulate
|
return accumulate
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,14 +59,14 @@ def session_method_wrapper(f):
|
||||||
url = self.endpoint + url
|
url = self.endpoint + url
|
||||||
r = f(self, url, *args, **kwargs)
|
r = f(self, url, *args, **kwargs)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
raise HwcClientException(0, f"Sending request failed, error={ex}")
|
raise HwcClientException(0, f"Sending request failed, error={ex}") from ex
|
||||||
|
|
||||||
result = None
|
result = None
|
||||||
if r.content:
|
if r.content:
|
||||||
try:
|
try:
|
||||||
result = r.json()
|
result = r.json()
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
raise HwcClientException(0, f"Parsing response to json failed, error: {ex}")
|
raise HwcClientException(0, f"Parsing response to json failed, error: {ex}") from ex
|
||||||
|
|
||||||
code = r.status_code
|
code = r.status_code
|
||||||
if code not in [200, 201, 202, 203, 204, 205, 206, 207, 208, 226]:
|
if code not in [200, 201, 202, 203, 204, 205, 206, 207, 208, 226]:
|
||||||
|
|
@ -184,7 +184,7 @@ class Config:
|
||||||
try:
|
try:
|
||||||
url = client.get_endpoint(service_type=service_type, region_name=region, interface="public")
|
url = client.get_endpoint(service_type=service_type, region_name=region, interface="public")
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
raise HwcClientException(0, f"Getting endpoint failed, error={ex}")
|
raise HwcClientException(0, f"Getting endpoint failed, error={ex}") from ex
|
||||||
|
|
||||||
if url == "":
|
if url == "":
|
||||||
raise HwcClientException(0, f"Cannot find the endpoint for {service_type}")
|
raise HwcClientException(0, f"Cannot find the endpoint for {service_type}")
|
||||||
|
|
|
||||||
|
|
@ -214,11 +214,11 @@ def _token_request(module_params, payload):
|
||||||
|
|
||||||
return r["access_token"]
|
return r["access_token"]
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
raise KeycloakError(f"API returned invalid JSON when trying to obtain access token from {auth_url}: {e}")
|
raise KeycloakError(f"API returned invalid JSON when trying to obtain access token from {auth_url}: {e}") from e
|
||||||
except KeyError:
|
except KeyError as e:
|
||||||
raise KeycloakError(f"API did not include access_token field in response from {auth_url}")
|
raise KeycloakError(f"API did not include access_token field in response from {auth_url}") from e
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise KeycloakError(f"Could not obtain access token from {auth_url}: {e}", authError=e)
|
raise KeycloakError(f"Could not obtain access token from {auth_url}: {e}", authError=e) from e
|
||||||
|
|
||||||
|
|
||||||
def _request_token_using_credentials(module_params):
|
def _request_token_using_credentials(module_params):
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ def _env_then_dns_fallback(*args, **kwargs):
|
||||||
try:
|
try:
|
||||||
return socket.gethostbyaddr(socket.gethostbyname("ipa-ca"))[0]
|
return socket.gethostbyaddr(socket.gethostbyname("ipa-ca"))[0]
|
||||||
except Exception:
|
except Exception:
|
||||||
raise AnsibleFallbackNotFound
|
raise AnsibleFallbackNotFound from None # no need to pass the original exception's context since this is basically a special return value
|
||||||
|
|
||||||
|
|
||||||
class IPAClient:
|
class IPAClient:
|
||||||
|
|
|
||||||
|
|
@ -116,7 +116,7 @@ class LXDClient:
|
||||||
self._raise_err_from_json(resp_json)
|
self._raise_err_from_json(resp_json)
|
||||||
return resp_json
|
return resp_json
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
raise LXDClientException("cannot connect to the LXD server", err=e)
|
raise LXDClientException("cannot connect to the LXD server", err=e) from e
|
||||||
|
|
||||||
def _raise_err_from_json(self, resp_json):
|
def _raise_err_from_json(self, resp_json):
|
||||||
err_params = {}
|
err_params = {}
|
||||||
|
|
|
||||||
|
|
@ -322,4 +322,4 @@ def pritunl_auth_request(
|
||||||
validate_certs=validate_certs,
|
validate_certs=validate_certs,
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise PritunlException(e)
|
raise PritunlException(e) from e
|
||||||
|
|
|
||||||
|
|
@ -161,8 +161,8 @@ class CronVar:
|
||||||
except IOError:
|
except IOError:
|
||||||
# cron file does not exist
|
# cron file does not exist
|
||||||
return
|
return
|
||||||
except Exception:
|
except Exception as e:
|
||||||
raise CronVarError("Unexpected error:", sys.exc_info()[0])
|
raise CronVarError("Unexpected error:", sys.exc_info()[0]) from e
|
||||||
else:
|
else:
|
||||||
# using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME
|
# using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME
|
||||||
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True)
|
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True)
|
||||||
|
|
@ -218,8 +218,8 @@ class CronVar:
|
||||||
except OSError:
|
except OSError:
|
||||||
# cron file does not exist
|
# cron file does not exist
|
||||||
return False
|
return False
|
||||||
except Exception:
|
except Exception as e:
|
||||||
raise CronVarError("Unexpected error:", sys.exc_info()[0])
|
raise CronVarError("Unexpected error:", sys.exc_info()[0]) from e
|
||||||
|
|
||||||
def parse_for_var(self, line):
|
def parse_for_var(self, line):
|
||||||
lexer = shlex.shlex(line)
|
lexer = shlex.shlex(line)
|
||||||
|
|
|
||||||
|
|
@ -475,7 +475,7 @@ class JenkinsPlugin:
|
||||||
self.module.fail_json(msg=msg_status, details=info["msg"])
|
self.module.fail_json(msg=msg_status, details=info["msg"])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if dont_fail:
|
if dont_fail:
|
||||||
raise FailedInstallingWithPluginManager(e)
|
raise FailedInstallingWithPluginManager(e) from e
|
||||||
else:
|
else:
|
||||||
self.module.fail_json(msg=msg_exception, details=to_native(e))
|
self.module.fail_json(msg=msg_exception, details=to_native(e))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -775,7 +775,7 @@ class JIRA(StateModuleHelper):
|
||||||
try:
|
try:
|
||||||
content = base64.b64decode(content)
|
content = base64.b64decode(content)
|
||||||
except binascii.Error as e:
|
except binascii.Error as e:
|
||||||
raise Exception(f"Unable to base64 decode file content: {e}")
|
raise Exception(f"Unable to base64 decode file content: {e}") from e
|
||||||
|
|
||||||
lines = [
|
lines = [
|
||||||
f"--{boundary}",
|
f"--{boundary}",
|
||||||
|
|
|
||||||
|
|
@ -136,7 +136,7 @@ def download_url(module, url, dest):
|
||||||
with open(dest, "w") as f:
|
with open(dest, "w") as f:
|
||||||
shutil.copyfileobj(response, f)
|
shutil.copyfileobj(response, f)
|
||||||
except IOError as e:
|
except IOError as e:
|
||||||
raise ModuleError(f"Failed to write: {e}")
|
raise ModuleError(f"Failed to write: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
def install_overlay(module, name, list_url=None):
|
def install_overlay(module, name, list_url=None):
|
||||||
|
|
|
||||||
|
|
@ -296,12 +296,12 @@ def ss_parse(raw):
|
||||||
protocol, state, recv_q, send_q, local_addr_port, peer_addr_port = cells
|
protocol, state, recv_q, send_q, local_addr_port, peer_addr_port = cells
|
||||||
else:
|
else:
|
||||||
protocol, state, recv_q, send_q, local_addr_port, peer_addr_port, process = cells
|
protocol, state, recv_q, send_q, local_addr_port, peer_addr_port, process = cells
|
||||||
except ValueError:
|
except ValueError as e:
|
||||||
# unexpected stdout from ss
|
# unexpected stdout from ss
|
||||||
raise EnvironmentError(
|
raise EnvironmentError(
|
||||||
'Expected `ss` table layout "Netid, State, Recv-Q, Send-Q, Local Address:Port, Peer Address:Port" and'
|
'Expected `ss` table layout "Netid, State, Recv-Q, Send-Q, Local Address:Port, Peer Address:Port" and'
|
||||||
f'optionally "Process", but got something else: {line}'
|
f'optionally "Process", but got something else: {line}'
|
||||||
)
|
) from e
|
||||||
|
|
||||||
conns = regex_conns.search(local_addr_port)
|
conns = regex_conns.search(local_addr_port)
|
||||||
pids = regex_pid.findall(process)
|
pids = regex_pid.findall(process)
|
||||||
|
|
|
||||||
|
|
@ -210,8 +210,8 @@ class OSXDefaults:
|
||||||
elif data_type == "date":
|
elif data_type == "date":
|
||||||
try:
|
try:
|
||||||
return datetime.strptime(value.split("+")[0].strip(), "%Y-%m-%d %H:%M:%S")
|
return datetime.strptime(value.split("+")[0].strip(), "%Y-%m-%d %H:%M:%S")
|
||||||
except ValueError:
|
except ValueError as e:
|
||||||
raise OSXDefaultsException(f"Invalid date value: {value!r}. Required format yyy-mm-dd hh:mm:ss.")
|
raise OSXDefaultsException(f"Invalid date value: {value!r}. Required format yyy-mm-dd hh:mm:ss.") from e
|
||||||
elif data_type in ["int", "integer"]:
|
elif data_type in ["int", "integer"]:
|
||||||
if not OSXDefaults.is_int(value):
|
if not OSXDefaults.is_int(value):
|
||||||
raise OSXDefaultsException(f"Invalid integer value: {value!r}")
|
raise OSXDefaultsException(f"Invalid integer value: {value!r}")
|
||||||
|
|
@ -219,8 +219,8 @@ class OSXDefaults:
|
||||||
elif data_type == "float":
|
elif data_type == "float":
|
||||||
try:
|
try:
|
||||||
value = float(value)
|
value = float(value)
|
||||||
except ValueError:
|
except ValueError as e:
|
||||||
raise OSXDefaultsException(f"Invalid float value: {value!r}")
|
raise OSXDefaultsException(f"Invalid float value: {value!r}") from e
|
||||||
return value
|
return value
|
||||||
elif data_type == "array":
|
elif data_type == "array":
|
||||||
if not isinstance(value, list):
|
if not isinstance(value, list):
|
||||||
|
|
|
||||||
|
|
@ -212,8 +212,8 @@ def parse_subnet_cidr(cidr):
|
||||||
addr, prefixlen = cidr.split("/")
|
addr, prefixlen = cidr.split("/")
|
||||||
try:
|
try:
|
||||||
prefixlen = int(prefixlen)
|
prefixlen = int(prefixlen)
|
||||||
except ValueError:
|
except ValueError as e:
|
||||||
raise Exception(f"Wrong prefix length in CIDR expression {cidr}")
|
raise Exception(f"Wrong prefix length in CIDR expression {cidr}") from e
|
||||||
return addr, prefixlen
|
return addr, prefixlen
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -210,7 +210,7 @@ def act_on_sshkeys(target_state, module, packet_conn):
|
||||||
changed = True
|
changed = True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_msg = f"while trying to remove sshkey {k.label}, id {k.id} {target_state}, got error: {e}"
|
_msg = f"while trying to remove sshkey {k.label}, id {k.id} {target_state}, got error: {e}"
|
||||||
raise Exception(_msg)
|
raise Exception(_msg) from e
|
||||||
|
|
||||||
return {"changed": changed, "sshkeys": [serialize_sshkey(k) for k in matching_sshkeys]}
|
return {"changed": changed, "sshkeys": [serialize_sshkey(k) for k in matching_sshkeys]}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -126,7 +126,7 @@ class PSAdapter(metaclass=abc.ABCMeta):
|
||||||
try:
|
try:
|
||||||
regex = re.compile(pattern, flags)
|
regex = re.compile(pattern, flags)
|
||||||
except re.error as e:
|
except re.error as e:
|
||||||
raise PSAdapterError(f"'{pattern}' is not a valid regular expression: {e}")
|
raise PSAdapterError(f"'{pattern}' is not a valid regular expression: {e}") from e
|
||||||
|
|
||||||
return [p.pid for p in self._process_iter(*self.PATTERN_ATTRS) if self._matches_regex(p, regex)]
|
return [p.pid for p in self._process_iter(*self.PATTERN_ATTRS) if self._matches_regex(p, regex)]
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -371,8 +371,8 @@ class RHEVConn:
|
||||||
api = API(url=url, username=user, password=password, insecure=str(insecure_api))
|
api = API(url=url, username=user, password=password, insecure=str(insecure_api))
|
||||||
api.test()
|
api.test()
|
||||||
self.conn = api
|
self.conn = api
|
||||||
except Exception:
|
except Exception as e:
|
||||||
raise Exception("Failed to connect to RHEV-M.")
|
raise Exception("Failed to connect to RHEV-M.") from e
|
||||||
|
|
||||||
def __del__(self):
|
def __del__(self):
|
||||||
self.conn.disconnect()
|
self.conn.disconnect()
|
||||||
|
|
|
||||||
|
|
@ -242,8 +242,8 @@ def absent(schema_facts, cursor, schema, usage_roles, create_roles):
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
cursor.execute(f"drop schema {schema_facts[schema_key]['name']} restrict")
|
cursor.execute(f"drop schema {schema_facts[schema_key]['name']} restrict")
|
||||||
except pyodbc.Error:
|
except pyodbc.Error as e:
|
||||||
raise CannotDropError("Dropping schema failed due to dependencies.")
|
raise CannotDropError("Dropping schema failed due to dependencies.") from e
|
||||||
del schema_facts[schema_key]
|
del schema_facts[schema_key]
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -282,8 +282,8 @@ def absent(user_facts, cursor, user, roles):
|
||||||
update_roles(user_facts, cursor, user, user_facts[user_key]["roles"], user_facts[user_key]["default_roles"], [])
|
update_roles(user_facts, cursor, user, user_facts[user_key]["roles"], user_facts[user_key]["default_roles"], [])
|
||||||
try:
|
try:
|
||||||
cursor.execute(f"drop user {user_facts[user_key]['name']}")
|
cursor.execute(f"drop user {user_facts[user_key]['name']}")
|
||||||
except pyodbc.Error:
|
except pyodbc.Error as e:
|
||||||
raise CannotDropError("Dropping user failed due to dependencies.")
|
raise CannotDropError("Dropping user failed due to dependencies.") from e
|
||||||
del user_facts[user_key]
|
del user_facts[user_key]
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue