Skip to content
This repository has been archived by the owner on Jun 13, 2024. It is now read-only.

Refactor module_utils #223

Merged
merged 3 commits into from
Sep 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
55 changes: 35 additions & 20 deletions plugins/module_utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import copy
from datetime import datetime
import time
import os
Expand Down Expand Up @@ -63,11 +62,7 @@


def list_dict_str(value):
if isinstance(value, list):
return value
elif isinstance(value, dict):
return value
elif isinstance(value, string_types):
if isinstance(value, (list, dict, string_types)):
return value
raise TypeError

Expand Down Expand Up @@ -160,20 +155,6 @@ def list_dict_str(value):


class K8sAnsibleMixin(object):
_argspec_cache = None

@property
def argspec(self):
"""
Introspect the model properties, and return an Ansible module arg_spec dict.
:return: dict
"""
if self._argspec_cache:
return self._argspec_cache
argument_spec = copy.deepcopy(COMMON_ARG_SPEC)
argument_spec.update(copy.deepcopy(AUTH_ARG_SPEC))
self._argspec_cache = argument_spec
return self._argspec_cache

def get_api_client(self, **auth_params):
auth_params = auth_params or getattr(self, 'params', {})
Expand Down Expand Up @@ -395,3 +376,37 @@ def _resource_absent(resource):
else:
predicate = _resource_absent
return self._wait_for(resource, definition['metadata']['name'], definition['metadata'].get('namespace'), predicate, sleep, timeout, state)

def set_resource_definitions(self):
resource_definition = self.params.get('resource_definition')

self.resource_definitions = []

if resource_definition:
if isinstance(resource_definition, string_types):
try:
self.resource_definitions = yaml.safe_load_all(resource_definition)
except (IOError, yaml.YAMLError) as exc:
self.fail(msg="Error loading resource_definition: {0}".format(exc))
elif isinstance(resource_definition, list):
self.resource_definitions = resource_definition
else:
self.resource_definitions = [resource_definition]

src = self.params.get('src')
if src:
self.resource_definitions = self.load_resource_definitions(src)
try:
self.resource_definitions = [item for item in self.resource_definitions if item]
except AttributeError:
pass

if not resource_definition and not src:
implicit_definition = dict(
kind=self.kind,
apiVersion=self.api_version,
metadata=dict(name=self.name)
)
if self.namespace:
implicit_definition['metadata']['namespace'] = self.namespace
self.resource_definitions = [implicit_definition]
32 changes: 1 addition & 31 deletions plugins/module_utils/raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,12 @@

from ansible.module_utils.basic import missing_required_lib
from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC, COMMON_ARG_SPEC, RESOURCE_ARG_SPEC, NAME_ARG_SPEC
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_native
from ansible_collections.community.kubernetes.plugins.module_utils.common import KubernetesAnsibleModule
from ansible.module_utils.common.dict_transformations import dict_merge


try:
import yaml
from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ConflictError, ForbiddenError, KubernetesValidateMissing
import urllib3
except ImportError:
Expand Down Expand Up @@ -108,7 +106,6 @@ def __init__(self, k8s_kind=None, *args, **kwargs):
self.api_version = self.params.get('api_version')
self.name = self.params.get('name')
self.namespace = self.params.get('namespace')
resource_definition = self.params.get('resource_definition')
validate = self.params.get('validate')
if validate:
if LooseVersion(self.openshift_version) < LooseVersion("0.8.0"):
Expand All @@ -125,34 +122,7 @@ def __init__(self, k8s_kind=None, *args, **kwargs):
if self.apply:
if not HAS_K8S_APPLY:
self.fail_json(msg=missing_required_lib("openshift >= 0.9.2", reason="for apply"))

if resource_definition:
if isinstance(resource_definition, string_types):
try:
self.resource_definitions = yaml.safe_load_all(resource_definition)
except (IOError, yaml.YAMLError) as exc:
self.fail(msg="Error loading resource_definition: {0}".format(exc))
elif isinstance(resource_definition, list):
self.resource_definitions = resource_definition
else:
self.resource_definitions = [resource_definition]
src = self.params.get('src')
if src:
self.resource_definitions = self.load_resource_definitions(src)
try:
self.resource_definitions = [item for item in self.resource_definitions if item]
except AttributeError:
pass

if not resource_definition and not src:
implicit_definition = dict(
kind=self.kind,
apiVersion=self.api_version,
metadata=dict(name=self.name)
)
if self.namespace:
implicit_definition['metadata']['namespace'] = self.namespace
self.resource_definitions = [implicit_definition]
self.set_resource_definitions()

def flatten_list_kind(self, list_resource, definitions):
flattened = []
Expand Down
28 changes: 1 addition & 27 deletions plugins/module_utils/scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@

from ansible_collections.community.kubernetes.plugins.module_utils.common import AUTH_ARG_SPEC, RESOURCE_ARG_SPEC, NAME_ARG_SPEC
from ansible_collections.community.kubernetes.plugins.module_utils.common import KubernetesAnsibleModule
from ansible.module_utils.six import string_types

try:
import yaml
from openshift.dynamic.exceptions import NotFoundError
except ImportError:
pass
Expand Down Expand Up @@ -59,31 +57,7 @@ def __init__(self, k8s_kind=None, *args, **kwargs):
self.api_version = self.params.get('api_version')
self.name = self.params.get('name')
self.namespace = self.params.get('namespace')
resource_definition = self.params.get('resource_definition')

if resource_definition:
if isinstance(resource_definition, string_types):
try:
self.resource_definitions = yaml.safe_load_all(resource_definition)
except (IOError, yaml.YAMLError) as exc:
self.fail(msg="Error loading resource_definition: {0}".format(exc))
elif isinstance(resource_definition, list):
self.resource_definitions = resource_definition
else:
self.resource_definitions = [resource_definition]
src = self.params.get('src')
if src:
self.resource_definitions = self.load_resource_definitions(src)

if not resource_definition and not src:
implicit_definition = dict(
kind=self.kind,
apiVersion=self.api_version,
metadata=dict(name=self.name)
)
if self.namespace:
implicit_definition['metadata']['namespace'] = self.namespace
self.resource_definitions = [implicit_definition]
self.set_resource_definitions()

def execute_module(self):
definition = self.resource_definitions[0]
Expand Down
17 changes: 9 additions & 8 deletions plugins/modules/k8s_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@
description:
- Use to specify an object model.
- Use in conjunction with I(api_version), I(name), and I(namespace) to identify a specific object.
- If using I(label_selector), cannot be overridden.
- If using I(label_selectors), cannot be overridden.
type: str
default: Pod
name:
description:
- Use to specify an object name.
- Use in conjunction with I(api_version), I(kind) and I(namespace) to identify a specific object.
- Only one of I(name) or I(label_selector) may be provided.
- Only one of I(name) or I(label_selectors) may be provided.
type: str
label_selectors:
description:
- List of label selectors to use to filter results
- Only one of I(name) or I(label_selector) may be provided.
- Only one of I(name) or I(label_selectors) may be provided.
type: list
elements: str
container:
Expand Down Expand Up @@ -139,6 +139,7 @@ def argspec(self):

def execute_module(self):
name = self.params.get('name')
namespace = self.params.get('namespace')
label_selector = ','.join(self.params.get('label_selectors', {}))
if name and label_selector:
self.fail(msg='Only one of name or label_selectors can be provided')
Expand All @@ -148,16 +149,16 @@ def execute_module(self):
v1_pods = self.find_resource('Pod', 'v1', fail=True)

if 'log' not in resource.subresources:
if not self.params.get('name'):
if not name:
self.fail(msg='name must be provided for resources that do not support the log subresource')
instance = resource.get(name=self.params['name'], namespace=self.params.get('namespace'))
instance = resource.get(name=name, namespace=namespace)
label_selector = ','.join(self.extract_selectors(instance))
resource = v1_pods

if label_selector:
instances = v1_pods.get(namespace=self.params['namespace'], label_selector=label_selector)
instances = v1_pods.get(namespace=namespace, label_selector=label_selector)
if not instances.items:
self.fail(msg='No pods in namespace {0} matched selector {1}'.format(self.params['namespace'], label_selector))
self.fail(msg='No pods in namespace {0} matched selector {1}'.format(namespace, label_selector))
# This matches the behavior of kubectl when logging pods via a selector
name = instances.items[0].metadata.name
resource = v1_pods
Expand All @@ -168,7 +169,7 @@ def execute_module(self):

log = serialize_log(resource.log.get(
name=name,
namespace=self.params.get('namespace'),
namespace=namespace,
serialize=False,
**kwargs
))
Expand Down