Skip to content

Commit

Permalink
refactor: move module vars out of __init__ (#336)
Browse files Browse the repository at this point in the history
##### SUMMARY

- move module vars out of `__init__`
- add modules type hints
- catch hcloud exception for api calls
  • Loading branch information
jooola authored Sep 26, 2023
1 parent 4ae557c commit 94190ae
Show file tree
Hide file tree
Showing 33 changed files with 250 additions and 132 deletions.
57 changes: 40 additions & 17 deletions plugins/module_utils/hcloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@


import traceback
from typing import Any, Dict, Optional

from ansible.module_utils.basic import env_fallback, missing_required_lib
from ansible.module_utils.basic import (
AnsibleModule as AnsibleModuleBase,
env_fallback,
missing_required_lib,
)
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.vendor import hcloud
from ..module_utils.vendor.hcloud import APIException, Client, HCloudException
from ..module_utils.vendor.hcloud.actions import ActionException
from .version import version

HAS_REQUESTS = True
Expand All @@ -25,31 +31,48 @@
HAS_DATEUTIL = False


# Provide typing definitions to the AnsibleModule class
class AnsibleModule(AnsibleModuleBase):
params: dict


class AnsibleHCloud:
def __init__(self, module, represent):
represent: str

module: AnsibleModule

def __init__(self, module: AnsibleModule):
if not self.represent:
raise NotImplementedError(f"represent property is not defined for {self.__class__.__name__}")

self.module = module
self.represent = represent
self.result = {"changed": False, self.represent: None}
if not HAS_REQUESTS:
module.fail_json(msg=missing_required_lib("requests"))
if not HAS_DATEUTIL:
module.fail_json(msg=missing_required_lib("python-dateutil"))
self._build_client()

def fail_json_hcloud(self, exception, msg=None, params=None, **kwargs):
def fail_json_hcloud(
self,
exception: HCloudException,
msg: Optional[str] = None,
params: Any = None,
**kwargs,
) -> None:
last_traceback = traceback.format_exc()

failure = {}

if params is not None:
failure["params"] = params

if isinstance(exception, hcloud.APIException):
if isinstance(exception, APIException):
failure["message"] = exception.message
failure["code"] = exception.code
failure["details"] = exception.details

elif isinstance(exception, hcloud.actions.domain.ActionException):
elif isinstance(exception, ActionException):
failure["action"] = {k: getattr(exception.action, k) for k in exception.action.__slots__}

exception_message = to_native(exception)
Expand All @@ -60,15 +83,15 @@ def fail_json_hcloud(self, exception, msg=None, params=None, **kwargs):

self.module.fail_json(msg=msg, exception=last_traceback, failure=failure, **kwargs)

def _build_client(self):
self.client = hcloud.Client(
def _build_client(self) -> None:
self.client = Client(
token=self.module.params["api_token"],
api_endpoint=self.module.params["endpoint"],
application_name="ansible-module",
application_version=version,
)

def _mark_as_changed(self):
def _mark_as_changed(self) -> None:
self.result["changed"] = True

@classmethod
Expand All @@ -80,17 +103,17 @@ def base_module_arguments(cls):
"fallback": (env_fallback, ["HCLOUD_TOKEN"]),
"no_log": True,
},
"endpoint": {"type": "str", "default": "https://api.hetzner.cloud/v1"},
"endpoint": {
"type": "str",
"default": "https://api.hetzner.cloud/v1",
},
}

def _prepare_result(self):
"""Prepare the result for every module
:return: dict
"""
def _prepare_result(self) -> Dict[str, Any]:
"""Prepare the result for every module"""
return {}

def get_result(self):
def get_result(self) -> Dict[str, Any]:
if getattr(self, self.represent) is not None:
self.result[self.represent] = self._prepare_result()
return self.result
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,20 @@
type: dict
"""

from typing import Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.certificates import BoundCertificate


class AnsibleHCloudCertificate(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_certificate")
self.hcloud_certificate = None
represent = "hcloud_certificate"

hcloud_certificate: Optional[BoundCertificate] = None

def _prepare_result(self):
return {
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_certificate_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,20 @@
returned: always
type: dict
"""
from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.certificates import BoundCertificate


class AnsibleHCloudCertificateInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_certificate_info")
self.hcloud_certificate_info = None
represent = "hcloud_certificate_info"

hcloud_certificate_info: Optional[List[BoundCertificate]] = None

def _prepare_result(self):
certificates = []
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_datacenter_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,20 @@
sample: fsn1
"""

from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.datacenters import BoundDatacenter


class AnsibleHCloudDatacenterInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_datacenter_info")
self.hcloud_datacenter_info = None
represent = "hcloud_datacenter_info"

hcloud_datacenter_info: Optional[List[BoundDatacenter]] = None

def _prepare_result(self):
tmp = []
Expand Down
9 changes: 5 additions & 4 deletions plugins/modules/hcloud_firewall.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,19 +167,20 @@
"""

import time
from typing import Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import APIException, HCloudException
from ..module_utils.vendor.hcloud.firewalls.domain import FirewallRule
from ..module_utils.vendor.hcloud.firewalls import BoundFirewall, FirewallRule


class AnsibleHCloudFirewall(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_firewall")
self.hcloud_firewall = None
represent = "hcloud_firewall"

hcloud_firewall: Optional[BoundFirewall] = None

def _prepare_result(self):
return {
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_floating_ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,20 @@
mylabel: 123
"""

from typing import Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.floating_ips import BoundFloatingIP


class AnsibleHCloudFloatingIP(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_floating_ip")
self.hcloud_floating_ip = None
represent = "hcloud_floating_ip"

hcloud_floating_ip: Optional[BoundFloatingIP] = None

def _prepare_result(self):
server = None
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_floating_ip_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,20 @@
type: dict
"""

from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.floating_ips import BoundFloatingIP


class AnsibleHCloudFloatingIPInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_floating_ip_info")
self.hcloud_floating_ip_info = None
represent = "hcloud_floating_ip_info"

hcloud_floating_ip_info: Optional[List[BoundFloatingIP]] = None

def _prepare_result(self):
tmp = []
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_image_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,20 @@
type: dict
"""

from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.images import BoundImage


class AnsibleHCloudImageInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_image_info")
self.hcloud_image_info = None
represent = "hcloud_image_info"

hcloud_image_info: Optional[List[BoundImage]] = None

def _prepare_result(self):
tmp = []
Expand Down
14 changes: 9 additions & 5 deletions plugins/modules/hcloud_iso_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,20 @@
sample: "2024-12-01T00:00:00+00:00"
"""

from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.isos import BoundIso


class AnsibleHCloudIsoInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_iso_info")
self.hcloud_iso_info = None
represent = "hcloud_iso_info"

hcloud_iso_info: Optional[List[BoundIso]] = None

def _prepare_result(self):
tmp = []
Expand Down Expand Up @@ -139,8 +143,8 @@ def get_iso_infos(self):
include_wildcard_architecture=self.module.params.get("include_wildcard_architecture"),
)

except Exception as exception:
self.module.fail_json(msg=exception.message)
except HCloudException as exception:
self.fail_json_hcloud(exception)

@classmethod
def define_module(cls):
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_load_balancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,17 +141,20 @@
sample: false
"""

from typing import Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.load_balancers import BoundLoadBalancer


class AnsibleHCloudLoadBalancer(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_load_balancer")
self.hcloud_load_balancer = None
represent = "hcloud_load_balancer"

hcloud_load_balancer: Optional[BoundLoadBalancer] = None

def _prepare_result(self):
private_ipv4_address = (
Expand Down
9 changes: 6 additions & 3 deletions plugins/modules/hcloud_load_balancer_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,17 +274,20 @@
sample: false
"""

from typing import List, Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.load_balancers import BoundLoadBalancer


class AnsibleHCloudLoadBalancerInfo(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_load_balancer_info")
self.hcloud_load_balancer_info = None
represent = "hcloud_load_balancer_info"

hcloud_load_balancer_info: Optional[List[BoundLoadBalancer]] = None

def _prepare_result(self):
tmp = []
Expand Down
14 changes: 9 additions & 5 deletions plugins/modules/hcloud_load_balancer_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,23 @@
sample: 10.0.0.8
"""

from typing import Optional

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native

from ..module_utils.hcloud import AnsibleHCloud
from ..module_utils.vendor.hcloud import HCloudException
from ..module_utils.vendor.hcloud.load_balancers import BoundLoadBalancer, PrivateNet
from ..module_utils.vendor.hcloud.networks import BoundNetwork


class AnsibleHCloudLoadBalancerNetwork(AnsibleHCloud):
def __init__(self, module):
super().__init__(module, "hcloud_load_balancer_network")
self.hcloud_network = None
self.hcloud_load_balancer = None
self.hcloud_load_balancer_network = None
represent = "hcloud_load_balancer_network"

hcloud_network: Optional[BoundNetwork] = None
hcloud_load_balancer: Optional[BoundLoadBalancer] = None
hcloud_load_balancer_network: Optional[PrivateNet] = None

def _prepare_result(self):
return {
Expand Down
Loading

0 comments on commit 94190ae

Please sign in to comment.