def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(change_hostname_to=dict(required=True, type='str'), domainname=dict(required=True, type='str'), dns_servers=dict(required=True, type='list'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') change_hostname_to = module.params['change_hostname_to'] domainname = module.params['domainname'] dns_servers = module.params['dns_servers'] try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = configure_dns(host_system, change_hostname_to, domainname, dns_servers) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def get_all_virtual_machines(content): virtual_machines = get_all_objs(content, [vim.VirtualMachine]) _virtual_machines = {} for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" _mac_address = [] for dev in vm.config.hardware.device: if isinstance(dev, vim.vm.device.VirtualEthernetCard): _mac_address.append(dev.macAddress) virtual_machine = { summary.config.name: { "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address, "mac_address": _mac_address, "uuid": summary.config.uuid } } _virtual_machines.update(virtual_machine) return _virtual_machines
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(vmk_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') vmk_name = module.params['vmk_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = configure_vmkernel_ip_address(host_system, vmk_name, ip_address, subnet_mask) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def get_all_virtual_machines(content): virtual_machines = get_all_objs(content, [vim.VirtualMachine]) _virtual_machines = {} for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" _mac_address = [] for dev in vm.config.hardware.device: if isinstance(dev, vim.vm.device.VirtualEthernetCard): _mac_address.append(dev.macAddress) virtual_machine = { summary.config.name: { "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address, "mac_address": _mac_address, "uuid": summary.config.uuid } } _virtual_machines.update(virtual_machine) return _virtual_machines
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict(change_hostname_to=dict(required=True, type='str'), domainname=dict(required=True, type='str'), dns_servers=dict(required=True, type='list'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') change_hostname_to = module.params['change_hostname_to'] domainname = module.params['domainname'] dns_servers = module.params['dns_servers'] try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = configure_dns(host_system, change_hostname_to, domainname, dns_servers) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def __init__(self, module): super(VmwareDatastoreMaintenanceMgr, self).__init__(module) datastore_name = self.params.get('datastore') cluster_name = self.params.get('cluster_name') datastore_cluster = self.params.get('datastore_cluster') self.datastore_objs = [] if datastore_name: self.datastore_objs = [ self.find_datastore_by_name(datastore_name=datastore_name) ] elif cluster_name: cluster = find_cluster_by_name(self.content, cluster_name) if not cluster: self.module.fail_json( msg='Failed to find cluster "%(cluster_name)s".' % self.params) self.datastore_objs = cluster.datastore elif datastore_cluster: datastore_cluster_obj = get_all_objs(self.content, [vim.StoragePod]) if not datastore_cluster_obj: self.module.fail_json( msg= 'Failed to find datastore cluster "%(datastore_cluster)s".' % self.params) for datastore in datastore_cluster_obj.childEntity: self.datastore_objs.append(datastore) else: self.module.fail_json( msg= "Please select one of 'cluster_name', 'datastore' or 'datastore_cluster'." ) self.state = self.params.get('state')
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict(vmk_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') vmk_name = module.params['vmk_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = configure_vmkernel_ip_address(host_system, vmk_name, ip_address, subnet_mask) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(cluster_uuid=dict(required=False, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') new_cluster_uuid = module.params['cluster_uuid'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed, result, cluster_uuid = create_vsan_cluster(host_system, new_cluster_uuid) module.exit_json(changed=changed, result=result, cluster_uuid=cluster_uuid) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def find_dvspg_by_name(self): vmware_distributed_port_group = get_all_objs( self.content, [vim.dvs.DistributedVirtualPortgroup]) for dvspg in vmware_distributed_port_group: if dvspg.name == self.dvportgroup_name: return dvspg return None
def get_all_virtual_machines(self): """ Function to get all virtual machines and related configurations information """ virtual_machines = get_all_objs(self.content, [vim.VirtualMachine]) _virtual_machines = {} for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" _mac_address = [] all_devices = _get_vm_prop(vm, ('config', 'hardware', 'device')) if all_devices: for dev in all_devices: if isinstance(dev, vim.vm.device.VirtualEthernetCard): _mac_address.append(dev.macAddress) net_dict = {} vmnet = _get_vm_prop(vm, ('guest', 'net')) if vmnet: for device in vmnet: net_dict[device.macAddress] = dict() net_dict[device.macAddress]['ipv4'] = [] net_dict[device.macAddress]['ipv6'] = [] for ip_addr in device.ipAddress: if "::" in ip_addr: net_dict[device.macAddress]['ipv6'].append(ip_addr) else: net_dict[device.macAddress]['ipv4'].append(ip_addr) esxi_hostname = None if summary.runtime.host: esxi_hostname = summary.runtime.host.summary.config.name virtual_machine = { summary.config.name: { "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address, # Kept for backward compatibility "mac_address": _mac_address, # Kept for backward compatibility "uuid": summary.config.uuid, "vm_network": net_dict, "esxi_hostname": esxi_hostname, } } vm_type = self.module.params.get('vm_type') if vm_type == 'vm' and vm.config.template is False: _virtual_machines.update(virtual_machine) elif vm_type == 'template' and vm.config.template: _virtual_machines.update(virtual_machine) elif vm_type == 'all': _virtual_machines.update(virtual_machine) return _virtual_machines
def __init__(self, module, datacenter_name, cluster_name=None): """ Doctring: Init """ super(VmwareDrsGroupInfoManager, self).__init__(module) self.__datacenter_name = datacenter_name self.__datacenter_obj = None self.__cluster_name = cluster_name self.__cluster_obj = None self.__msg = 'Nothing to see here...' self.__result = dict() self.__changed = False if datacenter_name: datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter_name) self.cluster_obj_list = [] if datacenter_obj: folder = datacenter_obj.hostFolder self.cluster_obj_list = get_all_objs(self.content, [vim.ClusterComputeResource], folder) else: raise Exception("Datacenter '%s' not found" % self.__datacenter_name) if cluster_name: cluster_obj = self.find_cluster_by_name(cluster_name=self.__cluster_name) if cluster_obj is None: raise Exception("Cluster '%s' not found" % self.__cluster_name) else: self.cluster_obj_list = [cluster_obj]
def __init__(self, module): super(VmwareDrsFactManager, self).__init__(module) datacenter_name = self.params.get('datacenter', None) if datacenter_name: datacenter_obj = find_datacenter_by_name( self.content, datacenter_name=datacenter_name) self.cluster_obj_list = [] if datacenter_obj: folder = datacenter_obj.hostFolder self.cluster_obj_list = get_all_objs( self.content, [vim.ClusterComputeResource], folder) else: self.module.fail_json(changed=False, msg="Datacenter '%s' not found" % datacenter_name) cluster_name = self.params.get('cluster_name', None) if cluster_name: cluster_obj = self.find_cluster_by_name(cluster_name=cluster_name) if cluster_obj is None: self.module.fail_json(changed=False, msg="Cluster '%s' not found" % cluster_name) else: self.cluster_obj_list = [cluster_obj]
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(cluster_uuid=dict(required=False, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') new_cluster_uuid = module.params['cluster_uuid'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed, result, cluster_uuid = create_vsan_cluster( host_system, new_cluster_uuid) module.exit_json(changed=changed, result=result, cluster_uuid=cluster_uuid) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def sanitize_network_params(self): network_list = [] valid_state = ['new', 'present', 'absent'] if len(self.params['networks']) != 0: for network in self.params['networks']: if 'state' not in network or network['state'].lower() not in valid_state: self.module.fail_json(msg="Network adapter state not specified or invalid: '%s', valid values: " "%s" % (network.get('state', ''), valid_state)) # add new network adapter but no name specified if network['state'].lower() == 'new' and 'name' not in network and 'vlan' not in network: self.module.fail_json(msg="Please specify at least network name or VLAN name for adding new network adapter.") if network['state'].lower() == 'new' and 'mac' in network: self.module.fail_json(msg="networks.mac is used for vNIC reconfigure, but networks.state is set to 'new'.") if network['state'].lower() == 'present' and 'mac' not in network and 'label' not in network and 'device_type' not in network: self.module.fail_json(msg="Should specify 'mac', 'label' or 'device_type' parameter to reconfigure network adapter") if 'connected' in network: if not isinstance(network['connected'], bool): self.module.fail_json(msg="networks.connected parameter should be boolean.") if network['state'].lower() == 'new' and not network['connected']: network['start_connected'] = False if 'start_connected' in network: if not isinstance(network['start_connected'], bool): self.module.fail_json(msg="networks.start_connected parameter should be boolean.") if network['state'].lower() == 'new' and not network['start_connected']: network['connected'] = False # specified network does not exist if 'name' in network and not self.network_exists_by_name(network['name']): self.module.fail_json(msg="Network '%(name)s' does not exist." % network) elif 'vlan' in network: objects = get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup]) dvps = [x for x in objects if to_text(get_parent_datacenter(x).name) == to_text(self.params['datacenter'])] for dvp in dvps: if hasattr(dvp.config.defaultPortConfig, 'vlan') and \ isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \ str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']): network['name'] = dvp.config.name break if 'dvswitch_name' in network and \ dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \ dvp.config.name == network['vlan']: network['name'] = dvp.config.name break if dvp.config.name == network['vlan']: network['name'] = dvp.config.name break else: self.module.fail_json(msg="VLAN '%(vlan)s' does not exist." % network) if 'device_type' in network and network['device_type'] not in list(self.nic_device_type.keys()): self.module.fail_json(msg="Device type specified '%s' is invalid. " "Valid types %s " % (network['device_type'], list(self.nic_device_type.keys()))) if ('mac' in network and not is_mac(network['mac'])) or \ ('manual_mac' in network and not is_mac(network['manual_mac'])): self.module.fail_json(msg="Device MAC address '%s' or manual set MAC address %s is invalid. " "Please provide correct MAC address." % (network['mac'], network['manual_mac'])) network_list.append(network) return network_list
def get_all_virtual_machines(self): """ Function to get all virtual machines and related configurations information """ virtual_machines = get_all_objs(self.content, [vim.VirtualMachine]) _virtual_machines = {} for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" _mac_address = [] all_devices = _get_vm_prop(vm, ('config', 'hardware', 'device')) if all_devices: for dev in all_devices: if isinstance(dev, vim.vm.device.VirtualEthernetCard): _mac_address.append(dev.macAddress) net_dict = {} vmnet = _get_vm_prop(vm, ('guest', 'net')) if vmnet: for device in vmnet: net_dict[device.macAddress] = dict() net_dict[device.macAddress]['ipv4'] = [] net_dict[device.macAddress]['ipv6'] = [] for ip_addr in device.ipAddress: if "::" in ip_addr: net_dict[device.macAddress]['ipv6'].append(ip_addr) else: net_dict[device.macAddress]['ipv4'].append(ip_addr) esxi_hostname = None if summary.runtime.host: esxi_hostname = summary.runtime.host.summary.config.name virtual_machine = { summary.config.name: { "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address, # Kept for backward compatibility "mac_address": _mac_address, # Kept for backward compatibility "uuid": summary.config.uuid, "vm_network": net_dict, "esxi_hostname": esxi_hostname, } } vm_type = self.module.params.get('vm_type') if vm_type == 'vm' and vm.config.template is False: _virtual_machines.update(virtual_machine) elif vm_type == 'template' and vm.config.template: _virtual_machines.update(virtual_machine) elif vm_type == 'all': _virtual_machines.update(virtual_machine) return _virtual_machines
def find_host_system(self): if self.esxi_hostname: host_system_obj = self.find_hostsystem_by_name(host_name=self.esxi_hostname) if host_system_obj: return host_system_obj else: self.module.fail_json(msg="Failed to find ESXi %s" % self.esxi_hostname) host_system = get_all_objs(self.content, [vim.HostSystem]) return host_system.keys()[0]
def find_dvs_by_uuid(self, uuid): """ Find DVS by UUID Returns: DVS name """ dvs_list = get_all_objs(self.content, [vim.DistributedVirtualSwitch]) for dvs in dvs_list: if dvs.uuid == uuid: return dvs.summary.name return None
def find_host_system(self): if self.esxi_hostname: host_system_obj = self.find_hostsystem_by_name(host_name=self.esxi_hostname) if host_system_obj: return host_system_obj else: self.module.fail_json(msg="Failed to find ESXi %s" % self.esxi_hostname) host_system = get_all_objs(self.content, [vim.HostSystem]) return host_system.keys()[0]
def get_folder_by_name(self, folder_name): """ Function to get managed object of folder by name Returns: Managed object of folder by name """ folder_objs = get_all_objs(self.content, [vim.Folder]) for folder in folder_objs: if folder.name == folder_name: return folder return None
def get_folder_by_name(self, folder_name): """ Function to get managed object of folder by name Returns: Managed object of folder by name """ folder_objs = get_all_objs(self.content, [vim.Folder]) for folder in folder_objs: if folder.name == folder_name: return folder return None
def check_vswitch_configuration(self): host = get_all_objs(self.content, [vim.HostSystem]) if not host: self.module.fail_json(msg="Unable to find host") self.host_system = list(host.keys())[0] self.vss = find_vswitch_by_name(self.host_system, self.switch) if self.vss is None: return 'absent' else: return 'present'
def check_vswitch_configuration(self): host = get_all_objs(self.content, [vim.HostSystem]) if not host: self.module.fail_json(msg="Unable to find host") self.host_system = list(host.keys())[0] self.vss = find_vswitch_by_name(self.host_system, self.switch_name) if self.vss is None: return 'absent' else: return 'present'
def find_dvs_by_uuid(self, uuid=None): dvs_obj = None if uuid is None: return dvs_obj dvswitches = get_all_objs(self.content, [vim.DistributedVirtualSwitch]) for dvs in dvswitches: if dvs.uuid == uuid: dvs_obj = dvs break return dvs_obj
def gather_rp_facts(self): resource_pool_facts = [] rps = get_all_objs(self.content, [vim.ResourcePool]) for rp in rps: tmp_facts = dict( name=rp.name, cpu_allocation_reservation=rp.config.cpuAllocation.reservation, cpu_allocation_expandable_reservation=rp.config.cpuAllocation. expandableReservation, cpu_allocation_limit=rp.config.cpuAllocation.limit, cpu_allocation_shares=rp.config.cpuAllocation.shares.shares, cpu_allocation_shares_level=rp.config.cpuAllocation.shares. level, cpu_allocation_overhead_limit=rp.config.cpuAllocation. overheadLimit, mem_allocation_reservation=rp.config.memoryAllocation. reservation, mem_allocation_expandable_reservation=rp.config. memoryAllocation.expandableReservation, mem_allocation_limit=rp.config.memoryAllocation.limit, mem_allocation_shares=rp.config.memoryAllocation.shares.shares, mem_allocation_shares_level=rp.config.memoryAllocation.shares. level, mem_allocation_overhead_limit=rp.config.memoryAllocation. overheadLimit, owner=rp.owner.name, overall_status=rp.summary.runtime.overallStatus, runtime_cpu_reservation_used=rp.summary.runtime.cpu. reservationUsed, runtime_cpu_reservation_used_vm=rp.summary.runtime.cpu. reservationUsedForVm, runtime_cpu_unreserved_for_pool=rp.summary.runtime.cpu. unreservedForPool, runtime_cpu_unreserved_for_vm=rp.summary.runtime.cpu. unreservedForVm, runtime_cpu_overall_usage=rp.summary.runtime.cpu.overallUsage, runtime_cpu_max_usage=rp.summary.runtime.cpu.maxUsage, runtime_memory_reservation_used=rp.summary.runtime.memory. reservationUsed, runtime_memory_reservation_used_vm=rp.summary.runtime.memory. reservationUsedForVm, runtime_memory_unreserved_for_pool=rp.summary.runtime.memory. unreservedForPool, runtime_memory_unreserved_for_vm=rp.summary.runtime.memory. unreservedForVm, runtime_memory_overall_usage=rp.summary.runtime.memory. overallUsage, runtime_memory_max_usage=rp.summary.runtime.memory.maxUsage, ) resource_pool_facts.append(tmp_facts) return resource_pool_facts
def select_resource_pool(self, host): pool_obj = None resource_pools = get_all_objs(self.content, [vim.ResourcePool]) pool_selections = self.get_obj( [vim.ResourcePool], self.resource_pool, return_all=True) if pool_selections: for p in pool_selections: if p in resource_pools: pool_obj = p break return pool_obj
def select_resource_pool(self, host): pool_obj = None resource_pools = get_all_objs(self.content, [vim.ResourcePool]) pool_selections = self.get_obj( [vim.ResourcePool], self.resource_pool, return_all=True) if pool_selections: for p in pool_selections: if p in resource_pools: pool_obj = p break return pool_obj
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict(portgroup_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'), mtu=dict(required=False, type='int'), enable_vsan=dict(required=False, type='bool'), enable_vmotion=dict(required=False, type='bool'), enable_mgmt=dict(required=False, type='bool'), enable_ft=dict(required=False, type='bool'), vswitch_name=dict(required=True, type='str'), vlan_id=dict(required=True, type='int'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') port_group_name = module.params['portgroup_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] mtu = module.params['mtu'] enable_vsan = module.params['enable_vsan'] enable_vmotion = module.params['enable_vmotion'] enable_mgmt = module.params['enable_mgmt'] enable_ft = module.params['enable_ft'] vswitch_name = module.params['vswitch_name'] vlan_id = module.params['vlan_id'] try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = create_vmkernel_adapter(host_system, port_group_name, vlan_id, vswitch_name, ip_address, subnet_mask, mtu, enable_vsan, enable_vmotion, enable_mgmt, enable_ft) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def getvm_folder_paths(self): results = [] # compare the folder path of each VM against the search path vmList = get_all_objs(self.content, [vim.VirtualMachine]) for item in vmList.items(): vobj = item[0] if not isinstance(vobj.parent, vim.Folder): continue # Match by name or uuid if vobj.config.name == self.name or vobj.config.uuid == self.uuid: folderpath = self.get_vm_path(self.content, vobj) results.append(folderpath) return results
def get_listing(self, objtype): """retrieves simple list of object names per object type Returns: list of dictionaries holding object names """ objtype_name = str(objtype) + '_info' result = {objtype_name: []} objects = get_all_objs(self.content, VMWARE_TYPES[objtype]) for obj in list(objects): result[objtype_name].append(str(obj.name.encode('utf-8'))) result[objtype_name] = sorted(result[objtype_name]) return result
def get_all_objs(self, content, types, confine_to_datacenter=True): """ Wrapper around get_all_objs to set datacenter context """ objects = get_all_objs(content, types) if confine_to_datacenter: if hasattr(objects, 'items'): # resource pools come back as a dictionary for k, v in tuple(objects.items()): parent_dc = get_parent_datacenter(k) if parent_dc.name != self.dc_name: del objects[k] else: # everything else should be a list objects = [x for x in objects if get_parent_datacenter(x).name == self.dc_name] return objects
def get_all_objs(self, content, types, confine_to_datacenter=True): """ Wrapper around get_all_objs to set datacenter context """ objects = get_all_objs(content, types) if confine_to_datacenter: if hasattr(objects, 'items'): # resource pools come back as a dictionary for k, v in objects.items(): parent_dc = get_parent_datacenter(k) if parent_dc.name != self.dc_name: objects.pop(k, None) else: # everything else should be a list objects = [x for x in objects if get_parent_datacenter(x).name == self.dc_name] return objects
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict(portgroup_name=dict(required=True, type='str'), switch_name=dict(required=True, type='str'), vlan_id=dict(required=True, type='int'), network_policy=dict(required=False, type='dict', default={}))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') portgroup_name = module.params['portgroup_name'] switch_name = module.params['switch_name'] vlan_id = module.params['vlan_id'] promiscuous_mode = module.params['network_policy'].get( 'promiscuous_mode', None) forged_transmits = module.params['network_policy'].get( 'forged_transmits', None) mac_changes = module.params['network_policy'].get('mac_changes', None) try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: raise SystemExit("Unable to locate Physical Host.") host_system = host.keys()[0] if find_host_portgroup_by_name(host_system, portgroup_name): module.exit_json(changed=False) network_policy = create_network_policy(promiscuous_mode, forged_transmits, mac_changes) changed = create_port_group(host_system, portgroup_name, vlan_id, switch_name, network_policy) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def __init__(self, module): super(DVSPortgroupInfoManager, self).__init__(module) self.dc_name = self.params['datacenter'] self.dvs_name = self.params['dvswitch'] datacenter = self.find_datacenter_by_name(self.dc_name) if datacenter is None: self.module.fail_json(msg="Failed to find the datacenter %s" % self.dc_name) if self.dvs_name: # User specified specific dvswitch name to gather information dvsn = find_dvs_by_name(self.content, self.dvs_name) if dvsn is None: self.module.fail_json(msg="Failed to find the dvswitch %s" % self.dvs_name) self.dvsls = [dvsn] else: # default behaviour, gather information about all dvswitches self.dvsls = get_all_objs(self.content, [vim.DistributedVirtualSwitch], folder=datacenter.networkFolder)
def getvm_folder_paths(self, name=None, uuid=None): results = [] if not self.folders: self.getfolders() # compare the folder path of each VM against the search path vmList = get_all_objs(self.content, [vim.VirtualMachine]) for item in vmList.items(): vobj = item[0] if not isinstance(vobj.parent, vim.Folder): continue # Match by name or uuid if vobj.config.name == name or vobj.config.uuid == uuid: folderpath = compile_folder_path_for_object(vobj) results.append(folderpath) return results
def get_datastore_listing(self): """retrieves list of datastore names and types Returns: list of dictionaries holding datastore names and types """ result = {'datastore_info': []} objects = get_all_objs(self.content, VMWARE_TYPES['datastore']) for obj in list(objects): if isinstance(obj, vim.StoragePod): dstype = 'datastore_cluster' elif isinstance(obj, vim.Datastore): dstype = 'datastore' result['datastore_info'].append({'type': dstype, 'name': obj.name}) result['datastore_info'] = sorted(result['datastore_info'], key=lambda k: k['type'] + k['name']) return result
def get_folder_listing(self): """retrieves list of folders with their names and absolute paths Returns: list of dictionaries, where each dictionary represent folder and contains name and abolute path to the folder """ result = {'folder_info': []} objects = get_all_objs(self.content, VMWARE_TYPES['folder']) for folder in list(objects): # filter root folders for each type and discard folders that cannot hold VMs if folder.name in ['vm', 'network', 'datastore', 'host' ] or 'VirtualMachine' not in folder.childType: continue result['folder_info'].append(self.compose_absolute_path(folder)) result['folder_info'] = sorted(result['folder_info']) return result
def __init__(self, module): super(PyVmomiHelper, self).__init__(module) self.port_group_name = self.params['portgroup_name'] self.ip_address = self.params['network'].get('ip_address', None) self.subnet_mask = self.params['network'].get('subnet_mask', None) self.network_type = self.params['network']['type'] self.mtu = self.params['mtu'] self.enable_vsan = self.params['enable_vsan'] self.enable_vmotion = self.params['enable_vmotion'] self.enable_mgmt = self.params['enable_mgmt'] self.enable_ft = self.params['enable_ft'] self.vswitch_name = self.params['vswitch_name'] self.vlan_id = self.params['vlan_id'] # TODO: Add logic to select different hostsystem host = get_all_objs(self.content, [vim.HostSystem]) if not host: self.module.fail_json(msg="Unable to locate Physical Host.") self.host_system = host.keys()[0]
def get_folder(self, datacenter_name, folder_name, folder_type, parent_folder=None): """ Get managed object of folder by name Returns: Managed object of folder by name """ folder_objs = get_all_objs(self.content, [vim.Folder], parent_folder) for folder in folder_objs: if parent_folder: if folder.name == folder_name and \ self.datacenter_folder_type[folder_type].childType == folder.childType: return folder else: if folder.name == folder_name and \ self.datacenter_folder_type[folder_type].childType == folder.childType and \ folder.parent.parent.name == datacenter_name: # e.g. folder.parent.parent.name == /DC01/host/folder return folder return None
def getvm_folder_paths(self, name=None, uuid=None): results = [] if not self.folders: self.getfolders() # compare the folder path of each VM against the search path vmList = get_all_objs(self.content, [vim.VirtualMachine]) for item in vmList.items(): vobj = item[0] if not isinstance(vobj.parent, vim.Folder): continue # Match by name or uuid if vobj.config.name == name or vobj.config.uuid == uuid: folderpath = compile_folder_path_for_object(vobj) results.append(folderpath) return results
def __init__(self, module): super(VmwareDrsFactManager, self).__init__(module) datacenter_name = self.params.get('datacenter', None) if datacenter_name: datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter_name) self.cluster_obj_list = [] if datacenter_obj: folder = datacenter_obj.hostFolder self.cluster_obj_list = get_all_objs(self.content, [vim.ClusterComputeResource], folder) else: self.module.fail_json(changed=False, msg="Datacenter '%s' not found" % datacenter_name) cluster_name = self.params.get('cluster_name', None) if cluster_name: cluster_obj = self.find_cluster_by_name(cluster_name=cluster_name) if cluster_obj is None: self.module.fail_json(changed=False, msg="Cluster '%s' not found" % cluster_name) else: self.cluster_obj_list = [cluster_obj]
def check_vswitch_configuration(self): hosts = get_all_objs(self.content, [vim.HostSystem]) if not hosts: self.module.fail_json(msg="Unable to find host") desired_host_system = None if self.esxi_hostname: for host_system_obj, host_system_name in iteritems(hosts): if host_system_name == self.esxi_hostname: desired_host_system = host_system_obj if desired_host_system: self.host_system = desired_host_system else: self.host_system = list(hosts.keys())[0] self.vss = find_vswitch_by_name(self.host_system, self.switch) if self.vss is None: return 'absent' else: return 'present'
def __init__(self, module): super(VmwareDatastoreMaintenanceMgr, self).__init__(module) datastore_name = self.params.get('datastore') cluster_name = self.params.get('cluster_name') datastore_cluster = self.params.get('datastore_cluster') self.datastore_objs = [] if datastore_name: self.datastore_objs = [self.find_datastore_by_name(datastore_name=datastore_name)] elif cluster_name: cluster = find_cluster_by_name(self.content, cluster_name) if not cluster: self.module.fail_json(msg='Failed to find cluster "%(cluster_name)s".' % self.params) self.datastore_objs = cluster.datastore elif datastore_cluster: datastore_cluster_obj = get_all_objs(self.content, [vim.StoragePod]) if not datastore_cluster_obj: self.module.fail_json(msg='Failed to find datastore cluster "%(datastore_cluster)s".' % self.params) for datastore in datastore_cluster_obj.childEntity: self.datastore_objs.append(datastore) else: self.module.fail_json(msg="Please select one of 'cluster_name', 'datastore' or 'datastore_cluster'.") self.state = self.params.get('state')
def gather_rp_facts(self): resource_pool_facts = [] rps = get_all_objs(self.content, [vim.ResourcePool]) for rp in rps: tmp_facts = dict( name=rp.name, cpu_allocation_reservation=rp.config.cpuAllocation.reservation, cpu_allocation_expandable_reservation=rp.config.cpuAllocation.expandableReservation, cpu_allocation_limit=rp.config.cpuAllocation.limit, cpu_allocation_shares=rp.config.cpuAllocation.shares.shares, cpu_allocation_shares_level=rp.config.cpuAllocation.shares.level, cpu_allocation_overhead_limit=rp.config.cpuAllocation.overheadLimit, mem_allocation_reservation=rp.config.memoryAllocation.reservation, mem_allocation_expandable_reservation=rp.config.memoryAllocation.expandableReservation, mem_allocation_limit=rp.config.memoryAllocation.limit, mem_allocation_shares=rp.config.memoryAllocation.shares.shares, mem_allocation_shares_level=rp.config.memoryAllocation.shares.level, mem_allocation_overhead_limit=rp.config.memoryAllocation.overheadLimit, owner=rp.owner.name, overall_status=rp.summary.runtime.overallStatus, runtime_cpu_reservation_used=rp.summary.runtime.cpu.reservationUsed, runtime_cpu_reservation_used_vm=rp.summary.runtime.cpu.reservationUsedForVm, runtime_cpu_unreserved_for_pool=rp.summary.runtime.cpu.unreservedForPool, runtime_cpu_unreserved_for_vm=rp.summary.runtime.cpu.unreservedForVm, runtime_cpu_overall_usage=rp.summary.runtime.cpu.overallUsage, runtime_cpu_max_usage=rp.summary.runtime.cpu.maxUsage, runtime_memory_reservation_used=rp.summary.runtime.memory.reservationUsed, runtime_memory_reservation_used_vm=rp.summary.runtime.memory.reservationUsedForVm, runtime_memory_unreserved_for_pool=rp.summary.runtime.memory.unreservedForPool, runtime_memory_unreserved_for_vm=rp.summary.runtime.memory.unreservedForVm, runtime_memory_overall_usage=rp.summary.runtime.memory.overallUsage, runtime_memory_max_usage=rp.summary.runtime.memory.maxUsage, ) resource_pool_facts.append(tmp_facts) return resource_pool_facts
def get_all_virtual_machines(self): """ Get all virtual machines and related configurations information """ folder = self.params.get('folder') folder_obj = None if folder: folder_obj = self.content.searchIndex.FindByInventoryPath(folder) if not folder_obj: self.module.fail_json( msg="Failed to find folder specified by %(folder)s" % self.params) virtual_machines = get_all_objs(self.content, [vim.VirtualMachine], folder=folder_obj) _virtual_machines = [] for vm in virtual_machines: _ip_address = "" summary = vm.summary if summary.guest is not None: _ip_address = summary.guest.ipAddress if _ip_address is None: _ip_address = "" _mac_address = [] all_devices = _get_vm_prop(vm, ('config', 'hardware', 'device')) if all_devices: for dev in all_devices: if isinstance(dev, vim.vm.device.VirtualEthernetCard): _mac_address.append(dev.macAddress) net_dict = {} vmnet = _get_vm_prop(vm, ('guest', 'net')) if vmnet: for device in vmnet: net_dict[device.macAddress] = dict() net_dict[device.macAddress]['ipv4'] = [] net_dict[device.macAddress]['ipv6'] = [] for ip_addr in device.ipAddress: if "::" in ip_addr: net_dict[device.macAddress]['ipv6'].append(ip_addr) else: net_dict[device.macAddress]['ipv4'].append(ip_addr) esxi_hostname = None esxi_parent = None if summary.runtime.host: esxi_hostname = summary.runtime.host.summary.config.name esxi_parent = summary.runtime.host.parent cluster_name = None if esxi_parent and isinstance(esxi_parent, vim.ClusterComputeResource): cluster_name = summary.runtime.host.parent.name vm_attributes = dict() if self.module.params.get('show_attribute'): vm_attributes = self.get_vm_attributes(vm) vm_folder = "" vm_parent = vm.parent datacenter = None while isinstance(vm_parent, vim.Folder): vm_folder += "/{0}".format(vm_parent.name) vm_parent = vm_parent.parent if isinstance(vm_parent, vim.Datacenter): datacenter = vm_parent.name vm_folder = "/{0}{1}".format(vm_parent.name, vm_folder) vm_tags = list() if self.module.params.get('show_tag'): vm_tags = self.get_tag_info(vm) virtual_machine = { "guest_name": summary.config.name, "guest_fullname": summary.config.guestFullName, "power_state": summary.runtime.powerState, "ip_address": _ip_address, # Kept for backward compatibility "mac_address": _mac_address, # Kept for backward compatibility "uuid": summary.config.uuid, "vm_network": net_dict, "esxi_hostname": esxi_hostname, "datacenter": datacenter, "cluster": cluster_name, "attributes": vm_attributes, "tags": vm_tags, "folder": vm_folder, } vm_type = self.module.params.get('vm_type') is_template = _get_vm_prop(vm, ('config', 'template')) if vm_type == 'vm' and not is_template: _virtual_machines.append(virtual_machine) elif vm_type == 'template' and is_template: _virtual_machines.append(virtual_machine) elif vm_type == 'all': _virtual_machines.append(virtual_machine) return _virtual_machines
def find_hostsystem(content): host_system = get_all_objs(content, [vim.HostSystem]) for host in host_system: return host return None
def find_dvspg_by_name(self): vmware_distributed_port_group = get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup]) for dvspg in vmware_distributed_port_group: if dvspg.name == self.dvportgroup_name: return dvspg return None
def find_vm_by_name(self): virtual_machines = get_all_objs(self.content, [vim.VirtualMachine]) for vm in virtual_machines: if vm.name == self.vm_name: return vm return None