Skip to content

Commit

Permalink
including PR suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
mikemorency committed Jul 18, 2024
1 parent 8f3e9f8 commit f78599c
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 77 deletions.
93 changes: 46 additions & 47 deletions plugins/module_utils/vmware.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,9 @@ def is_vcenter(self):

def get_objs_by_name_or_moid(self, vimtype, name, return_all=False):
"""
Get any vsphere object associated with a given text name and vim type.
Get any vsphere objects associated with a given text name or MOID and vim type.
Different objects have different unique-ness requirements for the name parameter, so
you may get one or more objects back. The MOID should always be unique
Args:
vimtype: The type of object to search for
name: The name or the ID of the object to search for
Expand Down Expand Up @@ -288,27 +290,55 @@ def get_datacenter_detailed(self, name):
"""
return self.get_objs_by_name_or_moid([vim.Datacenter], name)

def get_vm_by_name(self, vm_name, fail_on_missing=False, name_match=None):
def get_vm_using_params(
self, name_param='name', uuid_param='uuid', moid_param='moid', fail_on_missing=False,
name_match_param='name_match', use_instance_uuid_param='use_instance_uuid'):
"""
Get the vms matching the given name. VM names may not be unique
in a given cluster.
TODO
Get the vms matching the common module params related to vm identification: name, uuid, or moid. Since
MOID and UUID are unique identifiers, they are tried first. If they are not set, a search by name is tried
which may give one or more vms.
This also supports the 'name_match' parameter and the 'use_instance_uuid' parameters. The VM identification
parameter keys can be changed if your module uses different keys, like vm_name instead of just name
Args:
vm_name: Name of the VM to search for
name_param: Set the prameter key that corredsponds to the VM name
uuid_param: Set the prameter key that corredsponds to the VM UUID
moid_param: Set the prameter key that corredsponds to the VM MOID
name_match_param: Set the prameter key that corredsponds to the name_match option
use_instance_uuid_param: Set the prameter key that corredsponds use_instance_uuid option
fail_on_missing: If true, an error will be thrown if no VMs are found
name_match: If provided, return list of one VM. Either 'first' or 'last'
Returns:
list(vm), or None if no matches were found
"""
vms = self.__get_objs_by_name([vim.VirtualMachine], vm_name)
if not vms and fail_on_missing:
self.module.fail_json("Unable to find VM with name %s" % vm_name)
if vms and name_match:
if name_match == 'first':
if self.params.get(moid_param):
_search_type, _search_id, _search_value = 'moid', moid_param, self.params.get(moid_param)
elif self.params.get(uuid_param):
_search_type, _search_id, _search_value = 'uuid', uuid_param, self.params.get(uuid_param)
elif self.params.get(name_param):
_search_type, _search_id, _search_value = 'name', name_param, self.params.get(name_param)
else:
self.module.fail_json("Could not find any supported VM identifier params (name, uuid, or moid)")

if _search_type == 'uuid':
_vm = self.si.content.searchIndex.FindByUuid(
instanceUuid=self.params.get(use_instance_uuid_param, True),
uuid=_search_value,
vmSearch=True
)
vms = [_vm] if _vm else None
else:
vms = self.get_objs_by_name_or_moid([vim.VirtualMachine], _search_value)

if vms and _search_type == 'name' and self.params.get(name_match_param):
if self.params.get(name_match_param) == 'first':
return [vms[0]]
elif name_match == 'last':
elif self.params.get(name_match_param) == 'last':
return [vms[-1]]
else:
self.module.fail_json("Unrecognized name_match option '%s' in get_vm_by_name method" % name_match)
self.module.fail_json("Unrecognized name_match option '%s' " % self.params.get(name_match_param))

if not vms and fail_on_missing:
self.module.fail_json("Unable to find VM with %s %s" % _search_id, _search_value)

return vms

Expand All @@ -322,7 +352,7 @@ def get_folder_by_name(self, folder_name, fail_on_missing=False):
Returns:
list(folder object) or None
"""
folder = self.__get_objs_by_name([vim.Folder], folder_name)
folder = self.get_objs_by_name_or_moid([vim.Folder], folder_name)
if not folder and fail_on_missing:
self.module.fail_json("Unable to find folder with name %s" % folder_name)
return folder
Expand Down Expand Up @@ -354,7 +384,7 @@ def get_datastore_by_name(self, ds_name, fail_on_missing=False):
Returns:
datastore object or None
"""
ds = self.__get_objs_by_name([vim.Datastore], ds_name, first_only=True)
ds = self.get_objs_by_name_or_moid([vim.Datastore], ds_name, first_only=True)
if not ds and fail_on_missing:
self.module.fail_json("Unable to find datastore with name %s" % ds_name)
return ds
Expand All @@ -369,38 +399,7 @@ def get_resource_pool_by_name(self, pool_name, fail_on_missing=False):
Returns:
resource pool object or None
"""
pool = self.__get_objs_by_name([vim.ResourcePool], pool_name, first_only=True)
pool = self.get_objs_by_name_or_moid([vim.ResourcePool], pool_name, first_only=True)
if not pool and fail_on_missing:
self.module.fail_json("Unable to find resource pool with name %s" % pool_name)
return pool

def get_vm_by_uuid(self, vm_uuid, use_instance_uuid=True, fail_on_missing=False):
"""
Search for a VM using the instance UUID or BIOS UUID. BIOS UUID is considered an older
approach and is not garunteed to be unique.
Args:
vm_uuid: The uuid of the instance to search for
use_instance_uuid: If false, search for the BIOS UUID instead of the instance UUID
fail_on_missing: If true, an error will be thrown if no VMs are found
"""
vm = self.si.content.searchIndex.FindByUuid(
instanceUuid=use_instance_uuid,
uuid=vm_uuid,
vmSearch=True
)
if not vm and fail_on_missing:
self.module.fail_json("Unable to find VM with UUID %s" % vm_uuid)
return vm

def get_vm_by_moid(self, vm_moid, fail_on_missing=False):
"""
Search for a VM using the instance MOID or moREF. MOID is common in the VMWare REST
API but still usable in the SOAP API.
Args:
vm_moid: The uuid of the instance to search for
fail_on_missing: If true, an error will be thrown if no VMs are found
"""
vm = VmomiSupport.templateOf('VirtualMachine')(vm_moid, self.si._stub)
if not vm and fail_on_missing:
self.module.fail_json("Unable to find VM with MOID %s" % vm_moid)
return vm
52 changes: 23 additions & 29 deletions plugins/modules/folder_template_from_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,6 @@ def __init__(self, module):
if not self.is_vcenter():
self.module.fail_json("Only VCenter clusters are supported for this module.")

self.vm_name = self.params.get("vm_name")
self.vm_uuid = self.params.get("vm_uuid")
self.vm_use_instance_uuid = self.params.get("vm_use_instance_uuid")
self.vm_moid = self.params.get("vm_moid")

self.template_name = self.params.get("template_name")

fq_folder_path = format_folder_path_as_vm_fq_path(
Expand All @@ -175,16 +170,11 @@ def __init__(self, module):
)
self.template_folder = self.get_folder_by_absolute_path(fq_folder_path, fail_on_missing=True)

self.vm_name_match = self.params.get("vm_name_match")
self.datastore = self.params.get("datastore")
self.resource_pool = self.params.get("resource_pool")
self.wait_for_template = self.params.get("wait_for_template")

def check_if_template_exists(self):
"""
Checks if a template with the given name and folder already exists
"""
templates = self.get_vm_by_name(self.template_name, fail_on_missing=False)
templates = self.get_vm_using_params(name_param='template_name', fail_on_missing=False)
if not templates:
return False

Expand All @@ -204,19 +194,18 @@ def __get_source_vm(self):
Uses the UUID, MOID, or name provided to find the source VM for the template. Returns an error if using the name,
multiple matches are found, and the user did not provide a name_match strategy.
"""
if self.vm_uuid:
vm = self.get_vm_by_uuid(self.vm_uuid, use_instance_uuid=self.vm_use_instance_uuid, fail_on_missing=True)

elif self.vm_moid:
vm = self.get_vm_by_moid(self.vm_moid, fail_on_missing=True)

elif self.vm_name:
vm = self.get_vm_by_name(self.vm_name, fail_on_missing=True, name_match=self.vm_name_match)
if len(vm) == 1:
vm = vm[0]
else:
self.module.fail_json("Multiple VMs found with name %s. Try using the vm_name_match or vm_uuid/vm_moid attributes." % self.vm_name)

vms = self.get_vm_using_params(
name_param='vm_name',
moid_param='vm_moid',
uuid_param='vm_uuid',
name_match_param='vm_name_match',
use_instance_uuid_param='vm_use_instance_uuid',
fail_on_missing=True)

if len(vms) != 1:
self.module.fail_json("Multiple VMs found during search. Try using the vm_name_match or vm_uuid/vm_moid attributes.")

vm = vm[0]
if vm.runtime.powerState != 'poweredOff':
self.module.fail_json(msg="VM must be in powered off state before creating a template from it.")

Expand All @@ -238,15 +227,20 @@ def create_template_in_folder(self):
spec=template_spec
)

if self.wait_for_template:
if self.params.get("wait_for_template"):
self.__wait_for_template(task)

def __create_template_location_spec(self):
template_location_spec = vim.vm.RelocateSpec()
if self.datastore:
template_location_spec.datastore = self.get_datastore_by_name(self.datastore, fail_on_missing=True)
if self.resource_pool:
template_location_spec.pool = self.get_resource_pool_by_name(self.resource_pool, fail_on_missing=True)
if self.params.get("datastore"):
template_location_spec.datastore = self.get_datastore_by_name(
self.params.get("datastore"),
fail_on_missing=True)

if self.params.get("resource_pool"):
template_location_spec.pool = self.get_resource_pool_by_name(
self.params.get("resource_pool"),
fail_on_missing=True)

return template_location_spec

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
run_on_simulator: false
template_folder: e2e-qe
vm_name: folder_template_from_vm_test
vm_name: "{{ tiny_prefix }}_folder_template_from_vm_test"
vm_name_match: first
template_name: "{{ vm_name }}_template"

Expand Down

0 comments on commit f78599c

Please sign in to comment.