Move diff and wait to perform_action (#375)

This primarily moves the diff and wait logic from the various service
methods to perform_action to eliminate code duplication. I also moved
the diff_objects function out of the service object and moved most of
the find_resource logic to a new resource client method. We ended up
with several modules creating a service object just to use one of these
methods, so it seemed to make sense to make these more accessible.
This commit is contained in:
Mike Graves
2022-02-14 08:19:36 -05:00
parent 3bf147580f
commit 25644ac192
11 changed files with 356 additions and 448 deletions

View File

@@ -27,9 +27,15 @@ except ImportError:
try:
import kubernetes
from kubernetes.dynamic.exceptions import (
ResourceNotFoundError,
ResourceNotUniqueError,
)
from kubernetes.dynamic.resource import Resource
except ImportError:
# Handled in module setup
pass
# kubernetes import error is handled in module setup
# This is defined only for the sake of Ansible's checked import requirement
Resource = Any # type: ignore
try:
import urllib3
@@ -198,6 +204,21 @@ class K8SClient:
def resources(self) -> List[Any]:
return self.client.resources
def resource(self, kind: str, api_version: str) -> Resource:
"""Fetch a kubernetes client resource.
This will attempt to find a kubernetes resource trying, in order, kind,
name, singular_name and short_names.
"""
for attribute in ["kind", "name", "singular_name"]:
try:
return self.client.resources.get(
**{"api_version": api_version, attribute: kind}
)
except (ResourceNotFoundError, ResourceNotUniqueError):
pass
return self.client.resources.get(api_version=api_version, short_names=[kind])
def _ensure_dry_run(self, params: Dict) -> Dict:
if self.dry_run:
params["dry_run"] = True