Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updates for guest customization spec #20

Merged
merged 2 commits into from
Jan 20, 2022
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
31 changes: 0 additions & 31 deletions create_vm.yml

This file was deleted.

38 changes: 0 additions & 38 deletions create_vm_uc1.yml

This file was deleted.

20 changes: 0 additions & 20 deletions delete_vm.yml

This file was deleted.

70 changes: 0 additions & 70 deletions generate_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,73 +34,3 @@ def parse_json_to_spec(json_files_dir='', spec_files_dir=''):
files = glob.glob(json_files_dir + '*json.json')
for file in files:
file_name = spec_files_dir + os.path.splitext(file)[0]

with open(file) as f:
data = json.loads(f.read())
print('--------------------------------')
spec = generate_spec(data)
with open(file_name + "_spec.json", 'w') as spec_file:
spec_file.write(json.dumps(spec))
print(json.dumps(spec, indent=4))
return spec


spec = parse_json_to_spec()
print(spec)

def clean_spec(self, spec):
if not isinstance(spec, dict):
raise ValueError(spec)
for k, v in spec.copy().items():
if isinstance(v, str):
if v.startswith('{{') and v.endswith('}}'):
if self.get(v[2:-2]):
spec[k] = self.get(v[2:-2])
else:
spec.pop(k)
elif isinstance(v, dict):
v = clean_spec(self,v)
if v:
spec[k] = v
else:
spec.pop(k)
elif isinstance(v,list) and k != 'required':
v = [clean_spec(self,i) for i in v]
if tuple(i for i in v if i):
spec[k] = v
else:
spec.pop(k)
print('-----------------------------------')

requirements = spec.get('required',())
# print(requirements)
# if not requirements:
# for k, v in spec.items():
# print(k,v,'////////////')
# if isinstance(v, dict) and v.get('required'):
# requirements.append(k)
# print(requirements)
# print(spec)
# print('++++++++++++++++++++++++++++++')
# print()
# print()
if not set(requirements) <= spec.keys() or not spec:
return {'required': requirements}
return spec


self = {'action': 'create', 'credentials': {'username': 'admin', 'password': 'Nutanix.123'},
'ip_address': '10.44.77.6', 'port': '9440', 'cluster_uuid': '0005d2b3-16d0-829d-4591-ac1f6b6f97e7',
'name': 'test', 'spec__name': 'test',
# 'spec__cluster_reference__uuid': '0005d2b3-16d0-829d-4591-ac1f6b6f97e7',
'wait': True, 'wait_timeout': 300, 'validate_certs': False,
'spec__resources__nic_list__is_connected': False,
'spec__cluster_reference__kind': 'cluster',
'spec__resources__nic_list__subnet_reference__kind': 'subnet',
'data': None, 'operations': None, 'uuid': None,
'cpu_properties': None,
'spec__cluster_reference__name': None,
'spec__resources__nic_list__subnet_reference__uuid': None,
'spec__resources__nic_list__subnet_reference__name': None, 'nic_list': None}

print(json.dumps(clean_spec(self,spec), indent=4))
6 changes: 5 additions & 1 deletion nutanix/ncp/plugins/module_utils/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,12 @@ def clean_spec(self, spec):
for key, value in spec.copy().items():
if isinstance(value, str):
if value.startswith('{{') and value.endswith('}}'):
value = getattr(self, value[2:-2], None)
value = value[2:-2]

value = getattr(self, value, None)
if value:
if key == 'guest_customization':
value = self.get_attr_spec(key, value)
spec[key] = value
else:
spec.pop(key)
Expand Down
50 changes: 46 additions & 4 deletions nutanix/ncp/plugins/module_utils/prism/vms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This file is part of Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from copy import deepcopy

from base64 import b64encode
from .prism import Prism


Expand All @@ -13,7 +13,8 @@ class VM(Prism):
def get_attr_spec(self, param, param_spec, **kwargs):
param_method_spec = {
"disk_list": VMDisk,
"nic_list": VMNetwork
"nic_list": VMNetwork,
"guest_customization": GuestCustomizationSpec
}

if param in param_method_spec:
Expand Down Expand Up @@ -48,7 +49,7 @@ def get_entity_by_name(self, name='', kind=''):
class VMSpec():

@staticmethod
def get_default_spec(self):
def get_default_spec():
raise NotImplementedError(
"Get Default Spec helper not implemented for {}".format(self.entity_type)
)
Expand Down Expand Up @@ -202,7 +203,6 @@ def __get_subnet_ref(self, name, **kwargs):

def _get_api_spec(self, param_spec, **kwargs):

_di_map = {}
final_nic_list = []
for nic_param in param_spec:
nic_final = self.get_default_spec()
Expand Down Expand Up @@ -231,3 +231,45 @@ def _get_api_spec(self, param_spec, **kwargs):

def __call__(self, param_spec, **kwargs):
return self._get_api_spec(param_spec, **kwargs)


class GuestCustomizationSpec(VMSpec):

@staticmethod
def get_default_spec():
return deepcopy(
{
"sysprep": {
"install_type": "",
"unattend_xml": "",
"custom_key_values": {},
},
"cloud_init": {
"meta_data": "",
"user_data": "",
"custom_key_values": {},
},
"is_overridable": ""
}
)

def _get_api_spec(self, param_spec, **kwargs):

gc_spec = self.get_default_spec()
script_file_path = param_spec["script_path"]
with open(script_file_path, "r") as f:
content = f.read()
content = b64encode(content)
type = param_spec["type"]
if type == "sysprep":
gc_spec[type]["unattend_xml"] = content
elif type == "cloud_init":
gc_spec[type]["user_data"] = content
gc_spec["is_overridable"] = param_spec.get("is_overridable")

self.remove_null_references(gc_spec)

return gc_spec

def __call__(self, param_spec, **kwargs):
return self._get_api_spec(param_spec, **kwargs)
8 changes: 7 additions & 1 deletion nutanix/ncp/plugins/modules/nutanix_vms.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,14 @@ def run_module():
type='bool', default=False, aliases=['memory_overcommit_enabled']),
spec__resources__memory_size_mib=dict(type='int', default=1, aliases=['memory_size_mib', 'memory_gb']),
metadata__categories_mapping=dict(type='dict', aliases=['categories']),
metadata__use_categories_mapping=dict(type='bool', aliases=['use_categories_mapping'], default=False)
metadata__use_categories_mapping=dict(
type='bool', aliases=['use_categories_mapping'], default=False),
spec__resources__guest_customization=dict(type='dict', aliases=['guest_customization'], options=dict(
type=dict(type="str", choices=["sysprep", "cloud_init"], default="sysprep"),
script_path=dict(type="str", required=True),
is_overridable=dict(type="bool", default=False)
))
))

module = BaseModule()
if module.params.get('spec__resources__memory_size_mib'):
Expand Down