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

Commit

Permalink
facts: unify facts in a single module (#62)
Browse files Browse the repository at this point in the history
* Add listing to helper classes.
* Return list of resources instead of single items.
* Fix unit tests.
* Modified playbook examples and add new one.
* Modify README representing the new facts module.

Fixes #56.
  • Loading branch information
tripledes authored and alexxa committed Jul 3, 2018
1 parent 24cca19 commit f6c6bad
Show file tree
Hide file tree
Showing 14 changed files with 285 additions and 294 deletions.
8 changes: 3 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@

- `lib`: Ansible modules files for KubeVirt management
- `kubevirt_raw`: Allow to manage KubeVirt resources, VirtualMachineInstance, VirtualMachine, VirtualMachineInstanceReplicaSet and VirtualMachineInstancePresets.
- `kubevirt_vmi_facts`: Gather information about a given VirtualMachineInstance and store it on `kubevirt_vmi` variable.
- `kubevirt_vm_facts`: Gather information about a given VirtualMachine and store it on `kubevirt_vm` variable.
- `kubevirt_vmirs_facts`: Gather information about a given VirtualMachineInstanceReplicaSet and store it on `kubevirt_vmirs` variable.
- `kubevirt_vmipreset_facts`: Gather information about a given VirtualMachineInstancePreset and store it on `kubevirt_vmipreset` variable.
- `kubevirt_facts`: Gather facts about a given resource.
- `kubevirt_vm_status`: Set an VirtualMachine to either `running` or `stopped`.
- `kubevirt_scale_vmirs`: Scale up or down a VirtualMachineInstanceReplilcaSet.
- `tests`: Ansible playbook examples and unit tests
Expand Down Expand Up @@ -72,6 +69,7 @@ Because the role is referenced, the `hello-underworld` role is able to make use
* [Virtual Machine Instance facts](tests/kubevirt_vmi_facts.yml)
* [Virtual Machine facts](tests/kubevirt_vm_facts.yml)
* [Virtual Machine Instance ReplicaSet facts](tests/kubevirt_vmirs_facts.yml)
* [All Virtual Machine Instance facts](tests/kubevirt_all_vmis_facts.yml)

## Local testing

Expand Down Expand Up @@ -168,7 +166,7 @@ $ ssh -i tests/kubevirt_rsa -p 27017 kubevirt@172.30.133.9

### Facts

* Once one of the previous resources has been created, the fact modules can be tested as well as follows:
* Once one of the previous resources has been created, the facts module can be tested as well as follows:

```shell
$ ansible-playbook tests/kubevirt_vm_facts.yml
Expand Down
19 changes: 11 additions & 8 deletions lib/ansible/module_utils/k8svirt/facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,18 @@
if hasattr(sys, '_called_from_test'):
sys.path.append('lib/ansible/module_utils/k8svirt')
from common import K8sVirtAnsibleModule
from helper import AUTH_ARG_SPEC, FACTS_ARG_SPEC, get_helper
from helper import AUTH_ARG_SPEC, FACTS_ARG_SPEC, get_helper, to_snake
else:
from ansible.module_utils.k8svirt.helper import get_helper, AUTH_ARG_SPEC,\
FACTS_ARG_SPEC
FACTS_ARG_SPEC, to_snake
from ansible.module_utils.k8svirt.common import K8sVirtAnsibleModule


class KubeVirtFacts(K8sVirtAnsibleModule):
""" KubeVirtFacts common class """
def __init__(self, kind, *args, **kwargs):
def __init__(self, *args, **kwargs):
""" Class constructor """
self._api_client = None
self._kind = kind
self._kubevirt_obj = None
super(KubeVirtFacts, self).__init__(*args, **kwargs)

Expand All @@ -40,16 +39,20 @@ def argspec(self):
def execute_module(self):
""" Gather the actual facts """
self._api_client = self.authenticate()
res_helper = get_helper(self._api_client, self._kind)
kind = to_snake(self.params.get('kind'))
res_helper = get_helper(self._api_client, kind)
try:
self._kubevirt_obj = res_helper.exists(
self.params.get('name'), self.params.get('namespace')
self._kubevirt_obj = res_helper.list(
namespace=self.params.get('namespace'),
name=self.params.get('name'),
field_selectors=self.params['field_selectors'],
label_selectors=self.params['label_selectors']
)
self._kubevirt_obj = copy.deepcopy(self.__resource_cleanup())
return self._kubevirt_obj
except ApiException as exc:
self.fail_json(msg='Failed to retrieve requested object',
error=exc.reason)
error=str(exc))

def __resource_cleanup(self, subdict=None):
""" Cleanup null keys """
Expand Down
116 changes: 112 additions & 4 deletions lib/ansible/module_utils/k8svirt/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,28 @@
'virtual_machine': "VirtualMachineHelper"
}

FACTS_ARG_SPEC = dict(
name=dict(type='str', required=True),
namespace=dict(type='str', required=True)
)
FACTS_ARG_SPEC = {
'name': {
'type': 'str',
'required': False
},
'namespace': {
'type': 'str',
'required': False
},
'kind': {
'type': 'str',
'required': False
},
'label_selectors': {
'type': 'list',
'default': []
},
'field_selectors': {
'type': 'list',
'default': []
}
}

COMMON_ARG_SPEC = {
'state': {
Expand Down Expand Up @@ -121,6 +139,28 @@ def exists(self, name, namespace):
return self.__client.read_namespaced_virtual_machine_instance(
name, namespace, exact=True)

def list(self, namespace=None, name=None, field_selectors=None,
label_selectors=None):
""" Return a VirtualMachineInstancesList """
result = None
if name:
result = self.exists(name, namespace)
elif not namespace:
result = self.list_all(field_selectors, label_selectors)
else:
result = self.__client.list_namespaced_virtual_machine_instance(
namespace=namespace,
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors))
return result

def list_all(self, field_selectors=None, label_selectors=None):
""" Return all VirtualMachineInstances in a list """
return self.__client.list_virtual_machine_instance_for_all_namespaces(
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)
)

def replace(self, body, namespace, name):
""" Replace VirtualMachineInstance resource """
current = self.exists(name, namespace)
Expand Down Expand Up @@ -160,6 +200,28 @@ def exists(self, name, namespace):
return self.__client.read_namespaced_virtual_machine(
name, namespace, exact=True)

def list(self, namespace=None, name=None, field_selectors=None,
label_selectors=None):
""" Return a VirtualMachineList """
result = None
if name:
result = self.exists(name, namespace)
elif not namespace:
result = self.list_all(field_selectors, label_selectors)
else:
result = self.__client.list_namespaced_virtual_machine(
namespace=namespace,
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors))
return result

def list_all(self, field_selectors=None, label_selectors=None):
""" Return all VirtualMachines in a list """
return self.__client.list_virtual_machine_for_all_namespaces(
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)
)

def replace(self, body, namespace, name):
""" Replace VirtualMachine resource """
current = self.exists(name, namespace)
Expand Down Expand Up @@ -202,6 +264,29 @@ def exists(self, name, namespace):
read_namespaced_virtual_machine_instance_replica_set(
name, namespace, exact=True))

def list(self, namespace=None, name=None, field_selectors=None,
label_selectors=None):
""" Return a VirtualMachineInstanceReplicaSetList """
result = None
if name:
result = self.exists(name, namespace)
elif not namespace:
result = self.list_all(field_selectors, label_selectors)
else:
result = (self.__client.
list_namespaced_virtual_machine_instance_replica_set(
namespace=namespace,
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)))
return result

def list_all(self, field_selectors=None, label_selectors=None):
""" Return all VirtualMachineInstanceReplicaSets in a list """
return (self.__client.
list_virtual_machine_instance_replica_set_for_all_namespaces(
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)))

def replace(self, body, namespace, name):
""" Replace VirtualMachineInstanceReplicaSet """
current = self.exists(name, namespace)
Expand Down Expand Up @@ -242,6 +327,29 @@ def exists(self, name, namespace):
return self.__client.read_namespaced_virtual_machine_instance_preset(
name, namespace, exact=True)

def list(self, namespace=None, name=None, field_selectors=None,
label_selectors=None):
""" Return a VirtualMachineInstancePresetList """
result = None
if name:
result = self.exists(name, namespace)
elif not namespace:
result = self.list_all(field_selectors, label_selectors)
else:
result = (self.__client.
list_namespaced_virtual_machine_instance_preset(
namespace=namespace,
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)))
return result

def list_all(self, field_selectors=None, label_selectors=None):
""" Return all VirtualMachineInstancePresets in a list """
return (self.__client.
list_virtual_machine_instance_preset_for_all_namespaces(
field_selectors=','.join(field_selectors),
label_selectors=','.join(label_selectors)))

def replace(self, body, namespace, name):
""" Replace VirtualMachineInstancePreSet """
current = self.exists(name, namespace)
Expand Down
117 changes: 117 additions & 0 deletions lib/ansible/modules/cloud/kubevirt/kubevirt_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2018, KubeVirt Team <@kubevirt>
# Apache License, Version 2.0
# (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)

ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}

DOCUMENTATION = '''
---
module: kubevirt_facts
short_description: Retrieve facts about KubeVirt resources
version_added: "2.5"
author: KubeVirt Team (@kubevirt)
description:
- Retrieve facts about KubeVirt resources
requirements:
- python >= 2.7
- kubevirt-python >= v0.6.0-177-gd265c3c
'''

EXAMPLES = '''
- name: Facts for testvm in vms namespace
kubevirt_facts:
name: testvm
namespace: vms
kind: VirtualMachine
register: testvm_facts
- debug:
var: testvm_facts
- name: Facts for all VMIs in the cluster
kubevirt_facts:
kind: VirtualMachineInstance
register: all_vmis
- debug:
var: all_vmis
- name: Facts for all VMIRS in vms namespace
kubevirt_facts:
kind: VirtualMachineInstanceReplicaSet
namespace: vms
register: all_vms_vmirs
- debug:
var: all_vms_vmirs
- name: Facts for all VMIS in vms namespace with label 'app = web'
kubevirt_facts:
kind: VirtualMachineInstance
namespace: vms
label_selector:
- app = web
register: all_vmis_app_web
- debug:
var: all_vmis_app_web
'''

RETURN = '''
items:
description: "Dictionary describing the requested resource.
Resource attributes are mapped to dictionary
keys, which can be found at the following URL:
U(http://www.kubevirt.io/api-reference/master/definitions.html)"
returned: On success.
type: complex
contains:
api_version:
description: The versioned schema of the object representation.
returned: success
type: str
kind:
description: The REST resource type this object represents.
returned: success
type: str
metadata:
description: "Metadata includes name, namespace, annotations,
labels, etc."
returned: success
type: dict
spec:
description: "Specific attributes of the object depending
on the I(api_version) and I(kind)."
returned: success
type: dict
status:
description: Current status details for the object.
returned: success
type: dict
'''

from ansible.module_utils.k8svirt.facts import KubeVirtFacts


def main():
""" Entry point. """
facts = KubeVirtFacts()
obj = facts.execute_module()

if 'items' not in obj:
obj = dict(items=[obj])

facts.exit_json(
changed=False,
ansible_facts=obj
)


if __name__ == '__main__':
main()
Loading

0 comments on commit f6c6bad

Please sign in to comment.