-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: extract client utils in its own module
- Loading branch information
Showing
3 changed files
with
59 additions
and
55 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# Copyright: (c) 2023, Hetzner Cloud GmbH <[email protected]> | ||
|
||
from __future__ import annotations | ||
|
||
from ansible.module_utils.basic import missing_required_lib | ||
|
||
from .vendor.hcloud import Client | ||
|
||
HAS_REQUESTS = True | ||
HAS_DATEUTIL = True | ||
|
||
try: | ||
import requests # pylint: disable=unused-import | ||
except ImportError: | ||
HAS_REQUESTS = False | ||
|
||
try: | ||
import dateutil # pylint: disable=unused-import | ||
except ImportError: | ||
HAS_DATEUTIL = False | ||
|
||
|
||
class ClientException(Exception): | ||
"""An error related to the client occurred.""" | ||
|
||
|
||
def client_check_required_lib(): | ||
if not HAS_REQUESTS: | ||
raise ClientException(missing_required_lib("requests")) | ||
if not HAS_DATEUTIL: | ||
raise ClientException(missing_required_lib("python-dateutil")) | ||
|
||
|
||
def client_get_by_name_or_id(client: Client, resource: str, param: str | int): | ||
""" | ||
Get a resource by name, and if not found by its ID. | ||
:param client: Client to use to make the call | ||
:param resource: Name of the resource client that implements both `get_by_name` and `get_by_id` methods | ||
:param param: Name or ID of the resource to query | ||
""" | ||
resource_client = getattr(client, resource) | ||
|
||
result = resource_client.get_by_name(param) | ||
if result is not None: | ||
return result | ||
|
||
# If the param is not a valid ID, prevent an unnecessary call to the API. | ||
try: | ||
int(param) | ||
except ValueError as exception: | ||
raise ClientException(f"resource ({resource.rstrip('s')}) does not exist: {param}") from exception | ||
|
||
return resource_client.get_by_id(param) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters