def update_storage_domains(self, disk_id): changed = False disk_service = self._service.service(disk_id) disk = disk_service.get() sds_service = self._connection.system_service().storage_domains_service() # Initiate move: if self._module.params['storage_domain']: new_disk_storage = search_by_name(sds_service, self._module.params['storage_domain']) changed = self.action( action='move', entity=disk, action_condition=lambda d: new_disk_storage.id != d.storage_domains[0].id, wait_condition=lambda d: d.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage.id, ), )['changed'] if self._module.params['storage_domains']: for sd in self._module.params['storage_domains']: new_disk_storage = search_by_name(sds_service, sd) changed = changed or self.action( action='copy', entity=disk, wait_condition=lambda disk: disk.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage.id, ), )['changed'] return changed
def _permissions_service(connection, module): if module.params['user_name']: service = connection.system_service().users_service() entity = search_by_name(service, module.params['user_name']) else: service = connection.system_service().groups_service() entity = search_by_name(service, module.params['group_name']) if entity is None: raise Exception("User/Group wasn't found.") return service.service(entity.id).permissions_service()
def build_entity(self): return otypes.Template( name=self._module.params['name'], cluster=otypes.Cluster( name=self._module.params['cluster'] ) if self._module.params['cluster'] else None, vm=otypes.Vm( name=self._module.params['vm'] ) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile( id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id ) if self._module.params['cpu_profile'] else None, os=otypes.OperatingSystem( type=self.param('operating_system'), ) if self.param('operating_system') else None, memory=convert_to_bytes( self.param('memory') ) if self.param('memory') else None, memory_policy=otypes.MemoryPolicy( guaranteed=convert_to_bytes(self.param('memory_guaranteed')), max=convert_to_bytes(self.param('memory_max')), ) if any(( self.param('memory_guaranteed'), self.param('memory_max') )) else None, )
def _attached_sds_service(self): # Get data center object of the storage domain: dcs_service = self._connection.system_service().data_centers_service() dc = search_by_name(dcs_service, self._module.params['data_center']) if dc is None: return dc_service = dcs_service.data_center_service(dc.id) return dc_service.storage_domains_service()
def _get_mac_pool(self): mac_pool = None if self._module.params.get('mac_pool'): mac_pool = search_by_name( self._connection.system_service().mac_pools_service(), self._module.params.get('mac_pool'), ) return mac_pool
def _get_sched_policy(self): sched_policy = None if self.param('scheduling_policy'): sched_policies_service = self._connection.system_service().scheduling_policies_service() sched_policy = search_by_name(sched_policies_service, self.param('scheduling_policy')) if not sched_policy: raise Exception("Scheduling policy '%s' was not found" % self.param('scheduling_policy')) return sched_policy
def _get_export_domain_service(self): provider_name = self._module.params['export_domain'] or self._module.params['image_provider'] export_sds_service = self._connection.system_service().storage_domains_service() export_sd = search_by_name(export_sds_service, provider_name) if export_sd is None: raise ValueError( "Export storage domain/Image Provider '%s' wasn't found." % provider_name ) return export_sds_service.service(export_sd.id)
def wait_for_import(module, templates_service): if module.params['wait']: start = time.time() timeout = module.params['timeout'] poll_interval = module.params['poll_interval'] while time.time() < start + timeout: template = search_by_name(templates_service, module.params['name']) if template: return template time.sleep(poll_interval)
def _login(self, storage_type, storage): if storage_type == 'iscsi': hosts_service = self._connection.system_service().hosts_service() host = search_by_name(hosts_service, self._module.params['host']) hosts_service.host_service(host.id).iscsi_login( iscsi=otypes.IscsiDetails( username=storage.get('username'), password=storage.get('password'), address=storage.get('address'), target=storage.get('target'), ), )
def _attached_sds_service(self, dc_name): # Get data center object of the storage domain: dcs_service = self._connection.system_service().data_centers_service() # Search the data_center name, if it does not exist, try to search by guid. dc = search_by_name(dcs_service, dc_name) if dc is None: dc = get_entity(dcs_service.service(dc_name)) if dc is None: return None dc_service = dcs_service.data_center_service(dc.id) return dc_service.storage_domains_service()
def update_storage_domains(self, disk_id): changed = False disk_service = self._service.service(disk_id) disk = disk_service.get() sds_service = self._connection.system_service().storage_domains_service() # We don't support move© for non file based storages: if disk.storage_type != otypes.DiskStorageType.IMAGE: return changed # Initiate move: if self._module.params['storage_domain']: new_disk_storage = search_by_name(sds_service, self._module.params['storage_domain']) changed = self.action( action='move', entity=disk, action_condition=lambda d: new_disk_storage.id != d.storage_domains[0].id, wait_condition=lambda d: d.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage.id, ), post_action=lambda _: time.sleep(self._module.params['poll_interval']), )['changed'] if self._module.params['storage_domains']: for sd in self._module.params['storage_domains']: new_disk_storage = search_by_name(sds_service, sd) changed = changed or self.action( action='copy', entity=disk, wait_condition=lambda disk: disk.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage.id, ), )['changed'] return changed
def _update_tag_assignments(self, entity, name): if self._module.params[name] is None: return entities_service = getattr(self._connection.system_service(), '%s_service' % name)() current_vms = [ vm.name for vm in entities_service.list(search='tag=%s' % self._module.params['name']) ] # Assign tags: for entity_name in self._module.params[name]: entity = search_by_name(entities_service, entity_name) tags_service = entities_service.service(entity.id).tags_service() current_tags = [tag.name for tag in tags_service.list()] # Assign the tag: if self._module.params['name'] not in current_tags: if not self._module.check_mode: tags_service.add(tag=otypes.Tag( name=self._module.params['name'], ), ) self.changed = True # Unassign tags: for entity_name in [ e for e in current_vms if e not in self._module.params[name] ]: if not self._module.check_mode: entity = search_by_name(entities_service, entity_name) tags_service = entities_service.service( entity.id).tags_service() tag_id = [ tag.id for tag in tags_service.list() if tag.name == self._module.params['name'] ][0] tags_service.tag_service(tag_id).remove() self.changed = True
def main(): argument_spec = ovirt_info_full_argument_spec( vm=dict(required=True), name=dict(default=None), ) module = AnsibleModule(argument_spec) is_old_facts = module._name == 'ovirt_nic_facts' if is_old_facts: module.deprecate( "The 'ovirt_nic_facts' module has been renamed to 'ovirt_nic_info', " "and the renamed one no longer returns ansible_facts", version='2.13') check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) vms_service = connection.system_service().vms_service() vm_name = module.params['vm'] vm = search_by_name(vms_service, vm_name) if vm is None: raise Exception("VM '%s' was not found." % vm_name) nics_service = vms_service.service(vm.id).nics_service() if module.params['name']: nics = [ e for e in nics_service.list() if fnmatch.fnmatch(e.name, module.params['name']) ] else: nics = nics_service.list() result = dict(ovirt_nics=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in nics ], ) if is_old_facts: module.exit_json(changed=False, ansible_facts=result) else: module.exit_json(changed=False, **result) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def _object_service(connection, module): object_type = module.params['object_type'] objects_service = _objects_service(connection, object_type) object_id = module.params['object_id'] if object_id is None: sdk_object = search_by_name(objects_service, module.params['object_name']) if sdk_object is None: raise Exception( "'%s' object '%s' was not found." % (module.params['object_type'], module.params['object_name'])) object_id = sdk_object.id return objects_service.service(object_id)
def main(): argument_spec = ovirt_facts_full_argument_spec( vm=dict(required=True), description=dict(default=None), snapshot_id=dict(default=None), ) module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) vms_service = connection.system_service().vms_service() vm_name = module.params['vm'] vm = search_by_name(vms_service, vm_name) if vm is None: raise Exception("VM '%s' was not found." % vm_name) snapshots_service = vms_service.service(vm.id).snapshots_service() if module.params['description']: snapshots = [ e for e in snapshots_service.list() if fnmatch.fnmatch(e.description, module.params['description']) ] elif module.params['snapshot_id']: snapshots = [ snapshots_service.snapshot_service(module.params['snapshot_id']).get() ] else: snapshots = snapshots_service.list() module.exit_json( changed=False, ansible_facts=dict( ovirt_snapshots=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in snapshots ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['restore', 'present', 'absent'], default='present', ), vm_name=dict(required=True), snapshot_id=dict(default=None), description=dict(default=None), use_memory=dict( default=None, type='bool', aliases=['restore_memory', 'save_memory'], ), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_if=[ ('state', 'absent', ['snapshot_id']), ('state', 'restore', ['snapshot_id']), ]) check_sdk(module) vm_name = module.params.get('vm_name') auth = module.params.pop('auth') connection = create_connection(auth) vms_service = connection.system_service().vms_service() vm = search_by_name(vms_service, vm_name) if not vm: module.fail_json( msg="Vm '{name}' doesn't exist.".format(name=vm_name), ) vm_service = vms_service.vm_service(vm.id) snapshots_service = vms_service.vm_service(vm.id).snapshots_service() try: state = module.params['state'] if state == 'present': ret = create_snapshot(module, vm_service, snapshots_service) elif state == 'restore': ret = restore_snapshot(module, vm_service, snapshots_service) elif state == 'absent': ret = remove_snapshot(module, vm_service, snapshots_service) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def _permissions_service(connection, module): if module.params['user_name']: service = connection.system_service().users_service() entity = next( iter( service.list(search='usrname={0}'.format('{0}@{1}'.format( module.params['user_name'], module.params['authz_name'])))), None) else: service = connection.system_service().groups_service() entity = search_by_name(service, module.params['group_name']) if entity is None: raise Exception("User/Group wasn't found.") return service.service(entity.id).permissions_service()
def main(): argument_spec = ovirt_facts_full_argument_spec( data_center=dict(required=True), name=dict(default=None), ) module = AnsibleModule(argument_spec) if module._name == 'ovirt_quotas_facts': module.deprecate("The 'ovirt_quotas_facts' module is being renamed 'ovirt_quota_facts'", version=2.8) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) datacenters_service = connection.system_service().data_centers_service() dc_name = module.params['data_center'] dc = search_by_name(datacenters_service, dc_name) if dc is None: raise Exception("Datacenter '%s' was not found." % dc_name) quotas_service = datacenters_service.service(dc.id).quotas_service() if module.params['name']: quotas = [ e for e in quotas_service.list() if fnmatch.fnmatch(e.name, module.params['name']) ] else: quotas = quotas_service.list() module.exit_json( changed=False, ansible_facts=dict( ovirt_quotas=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in quotas ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def build_entity(self): return otypes.Template( name=self._module.params['name'], cluster=otypes.Cluster( name=self._module.params['cluster'] ) if self._module.params['cluster'] else None, vm=otypes.Vm( name=self._module.params['vm'] ) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile( id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id ) if self._module.params['cpu_profile'] else None, )
def _object_service(connection, module): object_type = module.params['object_type'] objects_service = _objects_service(connection, object_type) object_id = module.params['object_id'] if object_id is None: sdk_object = search_by_name(objects_service, module.params['object_name']) if sdk_object is None: raise Exception( "'%s' object '%s' was not found." % ( module.params['object_type'], module.params['object_name'] ) ) object_id = sdk_object.id return objects_service.service(object_id)
def __attach_nics(self, entity): # Attach NICs to VM, if specified: nics_service = self._service.service(entity.id).nics_service() for nic in self.param('nics'): if search_by_name(nics_service, nic.get('name')) is None: if not self._module.check_mode: nics_service.add( otypes.Nic( name=nic.get('name'), interface=otypes.NicInterface( nic.get('interface', 'virtio')), vnic_profile=otypes.VnicProfile( id=self.__get_vnic_profile_id(nic), ) if nic.get('profile_name') else None, mac=otypes.Mac(address=nic.get('mac_address')) if nic.get('mac_address') else None, )) self.changed = True
def build_entity(self): return otypes.Template( id=self._module.params['id'], name=self._module.params['name'], cluster=otypes.Cluster(name=self._module.params['cluster']) if self._module.params['cluster'] else None, vm=otypes.Vm(name=self._module.params['vm']) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile(id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id) if self._module.params['cpu_profile'] else None, display=otypes.Display( smartcard_enabled=self.param('smartcard_enabled')) if self.param('smartcard_enabled') is not None else None, os=otypes.OperatingSystem(type=self.param('operating_system'), ) if self.param('operating_system') else None, memory=convert_to_bytes(self.param('memory')) if self.param('memory') else None, soundcard_enabled=self.param('soundcard_enabled'), usb=(otypes.Usb(enabled=self.param('usb_support'))) if self.param('usb_support') is not None else None, sso=(otypes.Sso( methods=[otypes.Method(id=otypes.SsoMethod.GUEST_AGENT )] if self.param('sso') else [])) if self.param('sso') is not None else None, time_zone=otypes.TimeZone(name=self.param('timezone'), ) if self.param('timezone') else None, version=otypes.TemplateVersion( base_template=self._get_base_template(), version_name=self.param('version').get('name'), ) if self.param('version') else None, memory_policy=otypes.MemoryPolicy( guaranteed=convert_to_bytes(self.param('memory_guaranteed')), ballooning=self.param('ballooning_enabled'), max=convert_to_bytes(self.param('memory_max')), ) if any((self.param('memory_guaranteed'), self.param('ballooning_enabled'), self.param('memory_max'))) else None, io=otypes.Io(threads=self.param('io_threads'), ) if self.param('io_threads') is not None else None, initialization=self.get_initialization(), )
def post_present(self, entity_id): if self.param('storage'): sds_service = self._connection.system_service( ).storage_domains_service() sd = search_by_name(sds_service, self.param('storage')) if sd is None: raise Exception("Storage '%s' was not found." % self.param('storage')) if entity_id not in [ sd_conn.id for sd_conn in self._connection.follow_link( sd.storage_connections) ]: scs_service = sds_service.storage_domain_service( sd.id).storage_connections_service() if not self._module.check_mode: scs_service.add(connection=otypes.StorageConnection( id=entity_id, ), ) self.changed = True
def post_present(self, entity_id): if self.param('storage'): sds_service = self._connection.system_service().storage_domains_service() sd = search_by_name(sds_service, self.param('storage')) if sd is None: raise Exception( "Storage '%s' was not found." % self.param('storage') ) if entity_id not in [ sd_conn.id for sd_conn in self._connection.follow_link(sd.storage_connections) ]: scs_service = sds_service.storage_domain_service(sd.id).storage_connections_service() if not self._module.check_mode: scs_service.add( connection=otypes.StorageConnection( id=entity_id, ), ) self.changed = True
def _permissions_service(connection, module): if module.params['user_name']: service = connection.system_service().users_service() entity = next( iter( service.list( search='usrname={0}'.format( '{0}@{1}'.format(module.params['user_name'], module.params['authz_name']) ) ) ), None ) else: service = connection.system_service().groups_service() entity = search_by_name(service, module.params['group_name']) if entity is None: raise Exception("User/Group wasn't found.") return service.service(entity.id).permissions_service()
def update_storage_domains(self, disk_id): changed = False disk_service = self._service.service(disk_id) disk = disk_service.get() sds_service = self._connection.system_service().storage_domains_service() # We don't support move© for non file based storages: if disk.storage_type != otypes.DiskStorageType.IMAGE: return changed # Initiate move: if self._module.params['storage_domain']: new_disk_storage_id = get_id_by_name(sds_service, self._module.params['storage_domain']) changed = self.action( action='move', entity=disk, action_condition=lambda d: new_disk_storage_id != d.storage_domains[0].id, wait_condition=lambda d: d.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage_id, ), post_action=lambda _: time.sleep(self._module.params['poll_interval']), )['changed'] if self._module.params['storage_domains']: for sd in self._module.params['storage_domains']: new_disk_storage = search_by_name(sds_service, sd) changed = changed or self.action( action='copy', entity=disk, action_condition=( lambda disk: new_disk_storage.id not in [sd.id for sd in disk.storage_domains] ), wait_condition=lambda disk: disk.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain( id=new_disk_storage.id, ), )['changed'] return changed
def __get_vnic_profile_id(self, nic): """ Return VNIC profile ID looked up by it's name, because there can be more VNIC profiles with same name, other criteria of filter is cluster. """ vnics_service = self._connection.system_service( ).vnic_profiles_service() clusters_service = self._connection.system_service().clusters_service() cluster = search_by_name(clusters_service, self.param('cluster')) profiles = [ profile for profile in vnics_service.list() if profile.name == nic.get('profile_name') ] cluster_networks = [ net.id for net in self._connection.follow_link(cluster.networks) ] try: return next(profile.id for profile in profiles if profile.network.id in cluster_networks) except StopIteration: raise Exception("Profile '%s' was not found in cluster '%s'" % (nic.get('profile_name'), self.param('cluster')))
def _object_service(connection, module): object_type = module.params['object_type'] objects_service = _objects_service(connection, object_type) if object_type == 'system': return objects_service object_id = module.params['object_id'] if object_id is None: sdk_object = search_by_name(objects_service, module.params['object_name']) if sdk_object is None: raise Exception( "'%s' object '%s' was not found." % (module.params['object_type'], module.params['object_name'])) object_id = sdk_object.id object_service = objects_service.service(object_id) if module.params['quota_name'] and object_type == 'data_center': quotas_service = object_service.quotas_service() return quotas_service.quota_service( get_id_by_name(quotas_service, module.params['quota_name'])) return object_service
def build_entity(self): return otypes.Template( name=self._module.params['name'], cluster=otypes.Cluster(name=self._module.params['cluster']) if self._module.params['cluster'] else None, vm=otypes.Vm(name=self._module.params['vm']) if self._module.params['vm'] else None, description=self._module.params['description'], cpu_profile=otypes.CpuProfile(id=search_by_name( self._connection.system_service().cpu_profiles_service(), self._module.params['cpu_profile'], ).id) if self._module.params['cpu_profile'] else None, os=otypes.OperatingSystem(type=self.param('operating_system'), ) if self.param('operating_system') else None, memory=convert_to_bytes(self.param('memory')) if self.param('memory') else None, memory_policy=otypes.MemoryPolicy( guaranteed=convert_to_bytes(self.param('memory_guaranteed')), max=convert_to_bytes(self.param('memory_max')), ) if any((self.param('memory_guaranteed'), self.param('memory_max'))) else None, )
def main(): argument_spec = ovirt_full_argument_spec( vm=dict(required=True), name=dict(default=None), ) module = AnsibleModule(argument_spec) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) vms_service = connection.system_service().vms_service() vm_name = module.params['vm'] vm = search_by_name(vms_service, vm_name) if vm is None: raise Exception("VM '%s' was not found." % vm_name) nics_service = vms_service.service(vm.id).nics_service() if module.params['name']: nics = [ e for e in nics_service.list() if fnmatch.fnmatch(e.name, module.params['name']) ] else: nics = nics_service.list() module.exit_json( changed=False, ansible_facts=dict( ovirt_nics=[ get_dict_of_struct(c) for c in nics ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( datacenter=dict(required=True), name=dict(default=None), ) module = AnsibleModule(argument_spec) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) datacenters_service = connection.system_service().data_centers_service() dc_name = module.params['datacenter'] dc = search_by_name(datacenters_service, dc_name) if dc is None: raise Exception("Datacenter '%s' was not found." % dc_name) quotas_service = datacenters_service.service(dc.id).quotas_service() if module.params['name']: quotas = [ e for e in quotas_service.list() if fnmatch.fnmatch(e.name, module.params['name']) ] else: quotas = quotas_service.list() module.exit_json( changed=False, ansible_facts=dict( ovirt_quotas=[ get_dict_of_struct(c) for c in quotas ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict(choices=['present', 'absent', 'plugged', 'unplugged'], default='present'), vm=dict(required=True), name=dict(required=True), interface=dict(default=None), profile=dict(default=None), network=dict(default=None), mac_address=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: # Locate the service that manages the virtual machines and use it to # search for the NIC: auth = module.params.pop('auth') connection = create_connection(auth) vms_service = connection.system_service().vms_service() # Locate the VM, where we will manage NICs: vm_name = module.params.get('vm') vm = search_by_name(vms_service, vm_name) if vm is None: raise Exception("VM '%s' was not found." % vm_name) # Locate the service that manages the virtual machines NICs: vm_service = vms_service.vm_service(vm.id) nics_service = vm_service.nics_service() vmnics_module = VmNicsModule( connection=connection, module=module, service=nics_service, ) # Find vNIC id of the network interface (if any): profile = module.params.get('profile') if profile and module.params['network']: cluster_name = get_link_name(connection, vm.cluster) dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0] networks_service = dcs_service.service(dc.id).networks_service() network = search_by_name(networks_service, module.params['network']) for vnic in connection.system_service().vnic_profiles_service( ).list(): if vnic.name == profile and vnic.network.id == network.id: vmnics_module.vnic_id = vnic.id # Handle appropriate action: state = module.params['state'] if state == 'present': ret = vmnics_module.create() elif state == 'absent': ret = vmnics_module.remove() elif state == 'plugged': vmnics_module.create() ret = vmnics_module.action( action='activate', action_condition=lambda nic: not nic.plugged, wait_condition=lambda nic: nic.plugged, ) elif state == 'unplugged': vmnics_module.create() ret = vmnics_module.action( action='deactivate', action_condition=lambda nic: nic.plugged, wait_condition=lambda nic: not nic.plugged, ) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), datacenter=dict(default=None, required=True), name=dict(default=None, required=True), description=dict(default=None), comment=dict(default=None), vlan_tag=dict(default=None, type='int'), vm_network=dict(default=None, type='bool'), mtu=dict(default=None, type='int'), clusters=dict(default=None, type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: connection = create_connection(module.params.pop('auth')) clusters_service = connection.system_service().clusters_service() networks_service = connection.system_service().networks_service() networks_module = NetworksModule( connection=connection, module=module, service=networks_service, ) state = module.params['state'] network = networks_module.search_entity( search_params={ 'name': module.params['name'], 'datacenter': module.params['datacenter'], }, ) if state == 'present': ret = networks_module.create(entity=network) # Update clusters networks: for param_cluster in module.params.get('clusters', []): cluster = search_by_name(clusters_service, param_cluster.get('name', None)) if cluster is None: raise Exception("Cluster '%s' was not found." % cluster_name) cluster_networks_service = clusters_service.service(cluster.id).networks_service() cluster_networks_module = ClusterNetworksModule( network_id=ret['id'], cluster_network=param_cluster, connection=connection, module=module, service=cluster_networks_service, ) if param_cluster.get('assigned', True): ret = cluster_networks_module.create() else: ret = cluster_networks_module.remove() elif state == 'absent': ret = networks_module.remove(entity=network) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(required=True), datacenter=dict(required=True), description=dict(default=None), cluster_threshold=dict(default=None, type='int', aliases=['cluster_soft_limit']), cluster_grace=dict(default=None, type='int', aliases=['cluster_hard_limit']), storage_threshold=dict(default=None, type='int', aliases=['storage_soft_limit']), storage_grace=dict(default=None, type='int', aliases=['storage_hard_limit']), clusters=dict(default=[], type='list'), storages=dict(default=[], type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) datacenters_service = connection.system_service().data_centers_service( ) dc_name = module.params['datacenter'] dc_id = getattr(search_by_name(datacenters_service, dc_name), 'id', None) if dc_id is None: raise Exception("Datacenter '%s' was not found." % dc_name) quotas_service = datacenters_service.service(dc_id).quotas_service() quotas_module = QuotasModule( connection=connection, module=module, service=quotas_service, ) state = module.params['state'] if state == 'present': ret = quotas_module.create() # Manage cluster limits: cl_limit_service = quotas_service.service( ret['id']).quota_cluster_limits_service() for cluster in module.params.get('clusters'): cl_limit_service.add(limit=otypes.QuotaClusterLimit( memory_limit=float(cluster.get('memory')), vcpu_limit=cluster.get('cpu'), cluster=search_by_name( connection.system_service().clusters_service(), cluster.get('name')), ), ) # Manage storage limits: sd_limit_service = quotas_service.service( ret['id']).quota_storage_limits_service() for storage in module.params.get('storages'): sd_limit_service.add(limit=otypes.QuotaStorageLimit( limit=storage.get('size'), storage_domain=search_by_name( connection.system_service().storage_domains_service(), storage.get('name')), )) elif state == 'absent': ret = quotas_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'exported', 'imported'], default='present', ), name=dict(default=None, required=True), vm=dict(default=None), description=dict(default=None), cluster=dict(default=None), cpu_profile=dict(default=None), disks=dict(default=[], type='list'), clone_permissions=dict(type='bool'), export_domain=dict(default=None), storage_domain=dict(default=None), exclusive=dict(type='bool'), image_provider=dict(default=None), image_disk=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) templates_service = connection.system_service().templates_service() templates_module = TemplatesModule( connection=connection, module=module, service=templates_service, ) state = module.params['state'] if state == 'present': ret = templates_module.create( result_state=otypes.TemplateStatus.OK, clone_permissions=module.params['clone_permissions'], ) elif state == 'absent': ret = templates_module.remove() elif state == 'exported': template = templates_module.search_entity() export_service = templates_module._get_export_domain_service() export_template = search_by_attributes(export_service.templates_service(), id=template.id) ret = templates_module.action( entity=template, action='export', action_condition=lambda t: export_template is None, wait_condition=lambda t: t is not None, post_action=templates_module.post_export_action, storage_domain=otypes.StorageDomain(id=export_service.get().id), exclusive=module.params['exclusive'], ) elif state == 'imported': template = templates_module.search_entity() if template: ret = templates_module.create( result_state=otypes.TemplateStatus.OK, ) else: kwargs = {} if module.params['image_provider']: kwargs.update( disk=otypes.Disk( name=module.params['image_disk'] ), template=otypes.Template( name=module.params['name'], ), import_as_template=True, ) if module.params['image_disk']: # We need to refresh storage domain to get list of images: templates_module._get_export_domain_service().images_service().list() glance_service = connection.system_service().openstack_image_providers_service() image_provider = search_by_name(glance_service, module.params['image_provider']) images_service = glance_service.service(image_provider.id).images_service() else: images_service = templates_module._get_export_domain_service().templates_service() template_name = module.params['image_disk'] or module.params['name'] entity = search_by_name(images_service, template_name) if entity is None: raise Exception("Image/template '%s' was not found." % template_name) images_service.service(entity.id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain'] ) if module.params['storage_domain'] else None, cluster=otypes.Cluster( name=module.params['cluster'] ) if module.params['cluster'] else None, **kwargs ) template = wait_for_import(module, templates_service) ret = { 'changed': True, 'id': template.id, 'template': get_dict_of_struct(template), } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(required=True), datacenter=dict(required=True), description=dict(default=None), cluster_threshold=dict(default=None, type='int', aliases=['cluster_soft_limit']), cluster_grace=dict(default=None, type='int', aliases=['cluster_hard_limit']), storage_threshold=dict(default=None, type='int', aliases=['storage_soft_limit']), storage_grace=dict(default=None, type='int', aliases=['storage_hard_limit']), clusters=dict(default=[], type='list'), storages=dict(default=[], type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) datacenters_service = connection.system_service().data_centers_service() dc_name = module.params['datacenter'] dc_id = getattr(search_by_name(datacenters_service, dc_name), 'id', None) if dc_id is None: raise Exception("Datacenter '%s' was not found." % dc_name) quotas_service = datacenters_service.service(dc_id).quotas_service() quotas_module = QuotasModule( connection=connection, module=module, service=quotas_service, ) state = module.params['state'] if state == 'present': ret = quotas_module.create() # Manage cluster limits: cl_limit_service = quotas_service.service(ret['id']).quota_cluster_limits_service() for cluster in module.params.get('clusters'): cl_limit_service.add( limit=otypes.QuotaClusterLimit( memory_limit=float(cluster.get('memory')), vcpu_limit=cluster.get('cpu'), cluster=search_by_name( connection.system_service().clusters_service(), cluster.get('name') ), ), ) # Manage storage limits: sd_limit_service = quotas_service.service(ret['id']).quota_storage_limits_service() for storage in module.params.get('storages'): sd_limit_service.add( limit=otypes.QuotaStorageLimit( limit=storage.get('size'), storage_domain=search_by_name( connection.system_service().storage_domains_service(), storage.get('name') ), ) ) elif state == 'absent': ret = quotas_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(aliases=['host'], required=True), bond=dict(default=None, type='dict'), interface=dict(default=None), networks=dict(default=None, type='list'), labels=dict(default=None, type='list'), check=dict(default=None, type='bool'), save=dict(default=None, type='bool'), ) module = AnsibleModule(argument_spec=argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() host_networks_module = HostNetworksModule( connection=connection, module=module, service=hosts_service, ) host = host_networks_module.search_entity() if host is None: raise Exception("Host '%s' was not found." % module.params['name']) bond = module.params['bond'] interface = module.params['interface'] networks = module.params['networks'] labels = module.params['labels'] nic_name = bond.get('name') if bond else module.params['interface'] host_service = hosts_service.host_service(host.id) nics_service = host_service.nics_service() nic = search_by_name(nics_service, nic_name) network_names = [network['name'] for network in networks or []] state = module.params['state'] if (state == 'present' and (nic is None or host_networks_module.has_update( nics_service.service(nic.id)))): # Remove networks which are attached to different interface then user want: attachments_service = host_service.network_attachments_service() # Append attachment ID to network if needs update: for a in attachments_service.list(): current_network_name = get_link_name(connection, a.network) if current_network_name in network_names: for n in networks: if n['name'] == current_network_name: n['id'] = a.id # Check if we have to break some bonds: removed_bonds = [] if nic is not None: for host_nic in nics_service.list(): if host_nic.bonding and nic.id in [ slave.id for slave in host_nic.bonding.slaves ]: removed_bonds.append(otypes.HostNic(id=host_nic.id)) # Assign the networks: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], removed_bonds=removed_bonds if removed_bonds else None, modified_bonds=[ otypes.HostNic( name=bond.get('name'), bonding=otypes.Bonding( options=get_bond_options(bond.get('mode'), bond.get('options')), slaves=[ otypes.HostNic(name=i) for i in bond.get('interfaces', []) ], ), ), ] if bond else None, modified_labels=[ otypes.NetworkLabel( id=str(name), host_nic=otypes.HostNic( name=bond.get('name') if bond else interface), ) for name in labels ] if labels else None, modified_network_attachments=[ otypes.NetworkAttachment( id=network.get('id'), network=otypes.Network( name=network['name']) if network['name'] else None, host_nic=otypes.HostNic( name=bond.get('name') if bond else interface), ip_address_assignments=[ otypes.IpAddressAssignment( assignment_method=otypes.BootProtocol( network.get('boot_protocol', 'none')), ip=otypes.Ip( address=network.get('address'), gateway=network.get('gateway'), netmask=network.get('netmask'), version=otypes.IpVersion( network.get('version')) if network.get('version') else None, ), ), ], ) for network in networks ] if networks else None, ) elif state == 'absent' and nic: attachments = [] nic_service = nics_service.nic_service(nic.id) attached_labels = set([ str(lbl.id) for lbl in nic_service.network_labels_service().list() ]) if networks: attachments_service = nic_service.network_attachments_service() attachments = attachments_service.list() attachments = [ attachment for attachment in attachments if get_link_name( connection, attachment.network) in network_names ] # Remove unmanaged networks: unmanaged_networks_service = host_service.unmanaged_networks_service( ) unmanaged_networks = [(u.id, u.name) for u in unmanaged_networks_service.list()] for net_id, net_name in unmanaged_networks: if net_name in network_names: if not module.check_mode: unmanaged_networks_service.unmanaged_network_service( net_id).remove() host_networks_module.changed = True # Need to check if there are any labels to be removed, as backend fail # if we try to send remove non existing label, for bond and attachments it's OK: if (labels and set(labels).intersection(attached_labels) ) or bond or attachments: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module. _action_save_configuration, check_connectivity=module.params['check'], removed_bonds=[ otypes.HostNic(name=bond.get('name'), ), ] if bond else None, removed_labels=[ otypes.NetworkLabel(id=str(name)) for name in labels ] if labels else None, removed_network_attachments=attachments if attachments else None, ) nic = search_by_name(nics_service, nic_name) module.exit_json( **{ 'changed': host_networks_module.changed, 'id': nic.id if nic else None, 'host_nic': get_dict_of_struct(nic), }) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_info_full_argument_spec( name=dict(default=None), host=dict(default=None), vm=dict(default=None), ) module = AnsibleModule(argument_spec) is_old_facts = module._name == 'ovirt_tag_facts' if is_old_facts: module.deprecate("The 'ovirt_tag_facts' module has been renamed to 'ovirt_tag_info', " "and the renamed one no longer returns ansible_facts", version='2.13') check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) tags_service = connection.system_service().tags_service() tags = [] all_tags = tags_service.list() if module.params['name']: tags.extend([ t for t in all_tags if fnmatch.fnmatch(t.name, module.params['name']) ]) if module.params['host']: hosts_service = connection.system_service().hosts_service() host = search_by_name(hosts_service, module.params['host']) if host is None: raise Exception("Host '%s' was not found." % module.params['host']) tags.extend([ tag for tag in hosts_service.host_service(host.id).tags_service().list() ]) if module.params['vm']: vms_service = connection.system_service().vms_service() vm = search_by_name(vms_service, module.params['vm']) if vm is None: raise Exception("Vm '%s' was not found." % module.params['vm']) tags.extend([ tag for tag in vms_service.vm_service(vm.id).tags_service().list() ]) if not (module.params['vm'] or module.params['host'] or module.params['name']): tags = all_tags result = dict( ovirt_tags=[ get_dict_of_struct( struct=t, connection=connection, fetch_nested=module.params['fetch_nested'], attributes=module.params['nested_attributes'], ) for t in tags ], ) if is_old_facts: module.exit_json(changed=False, ansible_facts=result) else: module.exit_json(changed=False, **result) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'attached', 'detached'], default='present' ), id=dict(default=None), name=dict(default=None, aliases=['alias']), vm_name=dict(default=None), vm_id=dict(default=None), size=dict(default=None), interface=dict(default=None,), storage_domain=dict(default=None), storage_domains=dict(default=None, type='list'), profile=dict(default=None), format=dict(default=None, choices=['raw', 'cow']), bootable=dict(default=None, type='bool'), shareable=dict(default=None, type='bool'), logical_unit=dict(default=None, type='dict'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: disk = None state = module.params['state'] connection = create_connection(module.params.pop('auth')) disks_service = connection.system_service().disks_service() disks_module = DisksModule( connection=connection, module=module, service=disks_service, ) lun = module.params.get('logical_unit') if lun: disk = _search_by_lun(disks_service, lun.get('id')) ret = None # First take care of creating the VM, if needed: if state == 'present' or state == 'detached' or state == 'attached': ret = disks_module.create( entity=disk, result_state=otypes.DiskStatus.OK if lun is None else None, ) ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id']) # We need to pass ID to the module, so in case we want detach/attach disk # we have this ID specified to attach/detach method: module.params['id'] = ret['id'] if disk is None else disk.id elif state == 'absent': ret = disks_module.remove() # If VM was passed attach/detach disks to/from the VM: if module.params['vm_id'] or module.params['vm_name'] and state != 'absent': vms_service = connection.system_service().vms_service() # If `vm_id` isn't specified, find VM by name: vm_id = module.params['vm_id'] if vm_id is None: vm_id = getattr(search_by_name(vms_service, module.params['vm_name']), 'id', None) if vm_id is None: module.fail_json( msg="VM don't exists, please create it first." ) disk_attachments_service = vms_service.vm_service(vm_id).disk_attachments_service() disk_attachments_module = DiskAttachmentsModule( connection=connection, module=module, service=disk_attachments_service, changed=ret['changed'] if ret else False, ) if state == 'present' or state == 'attached': ret = disk_attachments_module.create() if lun is None: wait( service=disk_attachments_service.service(ret['id']), condition=lambda d:follow_link(connection, d.disk).status == otypes.DiskStatus.OK, wait=module.params['wait'], timeout=module.params['timeout'], ) elif state == 'detached': ret = disk_attachments_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(default=None, aliases=['host'], required=True), bond=dict(default=None, type='dict'), interface=dict(default=None), networks=dict(default=None, type='list'), labels=dict(default=None, type='list'), check=dict(default=None, type='bool'), save=dict(default=None, type='bool'), ) module = AnsibleModule(argument_spec=argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() host_networks_module = HostNetworksModule( connection=connection, module=module, service=hosts_service, ) host = host_networks_module.search_entity() if host is None: raise Exception("Host '%s' was not found." % module.params['name']) bond = module.params['bond'] interface = module.params['interface'] networks = module.params['networks'] labels = module.params['labels'] nic_name = bond.get('name') if bond else module.params['interface'] host_service = hosts_service.host_service(host.id) nics_service = host_service.nics_service() nic = search_by_name(nics_service, nic_name) network_names = [network['name'] for network in networks or []] state = module.params['state'] if ( state == 'present' and (nic is None or host_networks_module.has_update(nics_service.service(nic.id))) ): # Remove networks which are attached to different interface then user want: attachments_service = host_service.network_attachments_service() # Append attachment ID to network if needs update: for a in attachments_service.list(): current_network_name = get_link_name(connection, a.network) if current_network_name in network_names: for n in networks: if n['name'] == current_network_name: n['id'] = a.id # Check if we have to break some bonds: removed_bonds = [] if nic is not None: for host_nic in nics_service.list(): if host_nic.bonding and nic.id in [slave.id for slave in host_nic.bonding.slaves]: removed_bonds.append(otypes.HostNic(id=host_nic.id)) # Assign the networks: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], removed_bonds=removed_bonds if removed_bonds else None, modified_bonds=[ otypes.HostNic( name=bond.get('name'), bonding=otypes.Bonding( options=get_bond_options(bond.get('mode'), bond.get('options')), slaves=[ otypes.HostNic(name=i) for i in bond.get('interfaces', []) ], ), ), ] if bond else None, modified_labels=[ otypes.NetworkLabel( id=str(name), host_nic=otypes.HostNic( name=bond.get('name') if bond else interface ), ) for name in labels ] if labels else None, modified_network_attachments=[ otypes.NetworkAttachment( id=network.get('id'), network=otypes.Network( name=network['name'] ) if network['name'] else None, host_nic=otypes.HostNic( name=bond.get('name') if bond else interface ), ip_address_assignments=[ otypes.IpAddressAssignment( assignment_method=otypes.BootProtocol( network.get('boot_protocol', 'none') ), ip=otypes.Ip( address=network.get('address'), gateway=network.get('gateway'), netmask=network.get('netmask'), version=otypes.IpVersion( network.get('version') ) if network.get('version') else None, ), ), ], ) for network in networks ] if networks else None, ) elif state == 'absent' and nic: attachments = [] nic_service = nics_service.nic_service(nic.id) attached_labels = set([str(lbl.id) for lbl in nic_service.network_labels_service().list()]) if networks: attachments_service = nic_service.network_attachments_service() attachments = attachments_service.list() attachments = [ attachment for attachment in attachments if get_link_name(connection, attachment.network) in network_names ] # Remove unmanaged networks: unmanaged_networks_service = host_service.unmanaged_networks_service() unmanaged_networks = [(u.id, u.name) for u in unmanaged_networks_service.list()] for net_id, net_name in unmanaged_networks: if net_name in network_names: if not module.check_mode: unmanaged_networks_service.unmanaged_network_service(net_id).remove() host_networks_module.changed = True # Need to check if there are any labels to be removed, as backend fail # if we try to send remove non existing label, for bond and attachments it's OK: if (labels and set(labels).intersection(attached_labels)) or bond or attachments: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], removed_bonds=[ otypes.HostNic( name=bond.get('name'), ), ] if bond else None, removed_labels=[ otypes.NetworkLabel(id=str(name)) for name in labels ] if labels else None, removed_network_attachments=attachments if attachments else None, ) nic = search_by_name(nics_service, nic_name) module.exit_json(**{ 'changed': host_networks_module.changed, 'id': nic.id if nic else None, 'host_nic': get_dict_of_struct(nic), }) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), cluster=dict(default=None, required=True), name=dict(default=None, required=True), description=dict(default=None), vm_enforcing=dict(default=None, type='bool'), vm_rule=dict(default=None, choices=['positive', 'negative', 'disabled']), host_enforcing=dict(default=None, type='bool'), host_rule=dict(default=None, choices=['positive', 'negative']), vms=dict(default=None, type='list'), hosts=dict(default=None, type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) if module._name == 'ovirt_affinity_groups': module.deprecate( "The 'ovirt_affinity_groups' module is being renamed 'ovirt_affinity_group'", version=2.8) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) # Check if unsupported parameters were passed: supported_41 = ('host_enforcing', 'host_rule', 'hosts') if not check_support( version='4.1', connection=connection, module=module, params=supported_41, ): module.fail_json( msg='Following parameters are supported since 4.1: {params}'. format(params=supported_41, )) clusters_service = connection.system_service().clusters_service() vms_service = connection.system_service().vms_service() hosts_service = connection.system_service().hosts_service() cluster_name = module.params['cluster'] cluster = search_by_name(clusters_service, cluster_name) if cluster is None: raise Exception("Cluster '%s' was not found." % cluster_name) cluster_service = clusters_service.cluster_service(cluster.id) affinity_groups_service = cluster_service.affinity_groups_service() # Fetch VM ids which should be assigned to affinity group: vm_ids = sorted([ get_id_by_name(vms_service, vm_name) for vm_name in module.params['vms'] ]) if module.params['vms'] is not None else None # Fetch host ids which should be assigned to affinity group: host_ids = sorted([ get_id_by_name(hosts_service, host_name) for host_name in module.params['hosts'] ]) if module.params['hosts'] is not None else None affinity_groups_module = AffinityGroupsModule( connection=connection, module=module, service=affinity_groups_service, vm_ids=vm_ids, host_ids=host_ids, ) state = module.params['state'] if state == 'present': ret = affinity_groups_module.create() elif state == 'absent': ret = affinity_groups_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'plugged', 'unplugged'], default='present' ), vm=dict(required=True), name=dict(required=True), interface=dict(default=None), profile=dict(default=None), network=dict(default=None), mac_address=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: # Locate the service that manages the virtual machines and use it to # search for the NIC: connection = create_connection(module.params.pop('auth')) vms_service = connection.system_service().vms_service() # Locate the VM, where we will manage NICs: vm_name = module.params.get('vm') vm = search_by_name(vms_service, vm_name) if vm is None: raise Exception("VM '%s' was not found." % vm_name) # Locate the service that manages the virtual machines NICs: vm_service = vms_service.vm_service(vm.id) nics_service = vm_service.nics_service() vmnics_module = VmNicsModule( connection=connection, module=module, service=nics_service, ) # Find vNIC id of the network interface (if any): profile = module.params.get('profile') if profile and module.params['network']: cluster_name = get_link_name(connection, vm.cluster) dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0] networks_service = dcs_service.service(dc.id).networks_service() network = search_by_name(networks_service, module.params['network']) for vnic in connection.system_service().vnic_profiles_service().list(): if vnic.name == profile and vnic.network.id == network.id: vmnics_module.vnic_id = vnic.id # Handle appropriate action: state = module.params['state'] if state == 'present': ret = vmnics_module.create() elif state == 'absent': ret = vmnics_module.remove() elif state == 'plugged': vmnics_module.create() ret = vmnics_module.action( action='activate', action_condition=lambda nic: not nic.plugged, wait_condition=lambda nic: nic.plugged, ) elif state == 'unplugged': vmnics_module.create() ret = vmnics_module.action( action='deactivate', action_condition=lambda nic: nic.plugged, wait_condition=lambda nic: not nic.plugged, ) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), data_center=dict(required=True), id=dict(default=None), name=dict(required=True), description=dict(default=None), comment=dict(default=None), external_provider=dict(default=None), vlan_tag=dict(default=None, type='int'), vm_network=dict(default=None, type='bool'), mtu=dict(default=None, type='int'), clusters=dict(default=None, type='list'), label=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: auth = module.params.pop('auth') connection = create_connection(auth) clusters_service = connection.system_service().clusters_service() networks_service = connection.system_service().networks_service() networks_module = NetworksModule( connection=connection, module=module, service=networks_service, ) state = module.params['state'] search_params = { 'name': module.params['name'], 'datacenter': module.params['data_center'], } if state == 'present': if module.params.get('external_provider'): ret = networks_module.import_external_network() else: ret = networks_module.create(search_params=search_params) # Update clusters networks: if module.params.get('clusters') is not None: for param_cluster in module.params.get('clusters'): cluster = search_by_name(clusters_service, param_cluster.get('name')) if cluster is None: raise Exception("Cluster '%s' was not found." % param_cluster.get('name')) cluster_networks_service = clusters_service.service(cluster.id).networks_service() cluster_networks_module = ClusterNetworksModule( network_id=ret['id'], cluster_network=param_cluster, connection=connection, module=module, service=cluster_networks_service, ) if param_cluster.get('assigned', True): ret = cluster_networks_module.create() else: ret = cluster_networks_module.remove() elif state == 'absent': ret = networks_module.remove(search_params=search_params) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(default=None, aliases=['host'], required=True), bond=dict(default=None, type='dict'), interface=dict(default=None), networks=dict(default=None, type='list'), labels=dict(default=None, type='list'), check=dict(default=None, type='bool'), save=dict(default=None, type='bool'), ) module = AnsibleModule(argument_spec=argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() host_networks_module = HostNetworksModule( connection=connection, module=module, service=hosts_service, ) host = host_networks_module.search_entity() if host is None: raise Exception("Host '%s' was not found." % module.params['name']) bond = module.params['bond'] interface = module.params['interface'] networks = module.params['networks'] labels = module.params['labels'] nic_name = bond.get('name') if bond else module.params['interface'] nics_service = hosts_service.host_service(host.id).nics_service() nic = search_by_name(nics_service, nic_name) state = module.params['state'] if ( state == 'present' and (nic is None or host_networks_module.has_update(nics_service.service(nic.id))) ): host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], modified_bonds=[ otypes.HostNic( name=bond.get('name'), bonding=otypes.Bonding( options=[ otypes.Option( name="mode", value=str(bond.get('mode')), ) ], slaves=[ otypes.HostNic(name=i) for i in bond.get('interfaces', []) ], ), ), ] if bond else None, modified_labels=[ otypes.NetworkLabel( name=str(name), host_nic=otypes.HostNic( name=bond.get('name') if bond else interface ), ) for name in labels ] if labels else None, modified_network_attachments=[ otypes.NetworkAttachment( network=otypes.Network( name=network['name'] ) if network['name'] else None, host_nic=otypes.HostNic( name=bond.get('name') if bond else interface ), ip_address_assignments=[ otypes.IpAddressAssignment( assignment_method=otypes.BootProtocol( network.get('boot_protocol', 'none') ), ip=otypes.Ip( address=network.get('address'), gateway=network.get('gateway'), netmask=network.get('netmask'), version=otypes.IpVersion( network.get('version') ) if network.get('version') else None, ), ), ], ) for network in networks ] if networks else None, ) elif state == 'absent' and nic: attachments_service = nics_service.nic_service(nic.id).network_attachments_service() attachments = attachments_service.list() if networks: network_names = [network['name'] for network in networks] attachments = [ attachment for attachment in attachments if get_link_name(connection, attachment.network) in network_names ] if labels or bond or attachments: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], removed_bonds=[ otypes.HostNic( name=bond.get('name'), ), ] if bond else None, removed_labels=[ otypes.NetworkLabel( name=str(name), ) for name in labels ] if labels else None, removed_network_attachments=list(attachments), ) nic = search_by_name(nics_service, nic_name) module.exit_json(**{ 'changed': host_networks_module.changed, 'id': nic.id if nic else None, 'host_nic': get_dict_of_struct(nic), }) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict(type='str', default='present', choices=['absent', 'plugged', 'present', 'unplugged']), vm=dict(type='str'), template=dict(type='str'), name=dict(type='str', required=True), interface=dict(type='str'), profile=dict(type='str'), network=dict(type='str'), mac_address=dict(type='str'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_one_of=[['vm', 'template']], ) check_sdk(module) try: # Locate the service that manages the virtual machines and use it to # search for the NIC: auth = module.params.pop('auth') connection = create_connection(auth) entity_name = None if module.params.get('vm'): # Locate the VM, where we will manage NICs: entity_name = module.params.get('vm') collection_service = connection.system_service().vms_service() elif module.params.get('template'): entity_name = module.params.get('template') collection_service = connection.system_service().templates_service() # TODO: We have to modify the search_by_name function to accept raise_error=True/False, entity = search_by_name(collection_service, entity_name) if entity is None: raise Exception("Vm/Template '%s' was not found." % entity_name) service = collection_service.service(entity.id) cluster_id = entity.cluster nics_service = service.nics_service() entitynics_module = EntityNicsModule( connection=connection, module=module, service=nics_service, ) # Find vNIC id of the network interface (if any): profile = module.params.get('profile') if profile and module.params['network']: cluster_name = get_link_name(connection, cluster_id) dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0] networks_service = dcs_service.service(dc.id).networks_service() network = next( (n for n in networks_service.list() if n.name == module.params['network']), None ) if network is None: raise Exception( "Network '%s' was not found in datacenter '%s'." % ( module.params['network'], dc.name ) ) for vnic in connection.system_service().vnic_profiles_service().list(): if vnic.name == profile and vnic.network.id == network.id: entitynics_module.vnic_id = vnic.id # Handle appropriate action: state = module.params['state'] if state == 'present': ret = entitynics_module.create() elif state == 'absent': ret = entitynics_module.remove() elif state == 'plugged': entitynics_module.create() ret = entitynics_module.action( action='activate', action_condition=lambda nic: not nic.plugged, wait_condition=lambda nic: nic.plugged, ) elif state == 'unplugged': entitynics_module.create() ret = entitynics_module.action( action='deactivate', action_condition=lambda nic: nic.plugged, wait_condition=lambda nic: not nic.plugged, ) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'exported', 'imported', 'registered'], default='present', ), id=dict(default=None), name=dict(default=None), vm=dict(default=None), description=dict(default=None), cluster=dict(default=None), allow_partial_import=dict(default=None, type='bool'), cpu_profile=dict(default=None), disks=dict(default=[], type='list'), clone_permissions=dict(type='bool'), export_domain=dict(default=None), storage_domain=dict(default=None), exclusive=dict(type='bool'), image_provider=dict(default=None), image_disk=dict(default=None, aliases=['glance_image_disk_name']), template_image_disk_name=dict(default=None), seal=dict(type='bool'), vnic_profile_mappings=dict(default=[], type='list'), cluster_mappings=dict(default=[], type='list'), role_mappings=dict(default=[], type='list'), domain_mappings=dict(default=[], type='list'), operating_system=dict(type='str'), memory=dict(type='str'), memory_guaranteed=dict(type='str'), memory_max=dict(type='str'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_one_of=[['id', 'name']], ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) templates_service = connection.system_service().templates_service() templates_module = TemplatesModule( connection=connection, module=module, service=templates_service, ) state = module.params['state'] if state == 'present': ret = templates_module.create( result_state=otypes.TemplateStatus.OK, clone_permissions=module.params['clone_permissions'], seal=module.params['seal'], ) elif state == 'absent': ret = templates_module.remove() elif state == 'exported': template = templates_module.search_entity() export_service = templates_module._get_export_domain_service() export_template = search_by_attributes(export_service.templates_service(), id=template.id) ret = templates_module.action( entity=template, action='export', action_condition=lambda t: export_template is None or module.params['exclusive'], wait_condition=lambda t: t is not None, post_action=templates_module.post_export_action, storage_domain=otypes.StorageDomain(id=export_service.get().id), exclusive=module.params['exclusive'], ) elif state == 'imported': template = templates_module.search_entity() if template: ret = templates_module.create( result_state=otypes.TemplateStatus.OK, ) else: kwargs = {} if module.params['image_provider']: kwargs.update( disk=otypes.Disk( name=module.params['template_image_disk_name'] or module.params['image_disk'] ), template=otypes.Template( name=module.params['name'], ), import_as_template=True, ) if module.params['image_disk']: # We need to refresh storage domain to get list of images: templates_module._get_export_domain_service().images_service().list() glance_service = connection.system_service().openstack_image_providers_service() image_provider = search_by_name(glance_service, module.params['image_provider']) images_service = glance_service.service(image_provider.id).images_service() else: images_service = templates_module._get_export_domain_service().templates_service() template_name = module.params['image_disk'] or module.params['name'] entity = search_by_name(images_service, template_name) if entity is None: raise Exception("Image/template '%s' was not found." % template_name) images_service.service(entity.id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain'] ) if module.params['storage_domain'] else None, cluster=otypes.Cluster( name=module.params['cluster'] ) if module.params['cluster'] else None, **kwargs ) # Wait for template to appear in system: template = templates_module.wait_for_import( condition=lambda t: t.status == otypes.TemplateStatus.OK ) ret = templates_module.create(result_state=otypes.TemplateStatus.OK) ret = { 'changed': True, 'id': template.id, 'template': get_dict_of_struct(template), } elif state == 'registered': storage_domains_service = connection.system_service().storage_domains_service() # Find the storage domain with unregistered template: sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain']) storage_domain_service = storage_domains_service.storage_domain_service(sd_id) templates_service = storage_domain_service.templates_service() # Find the unregistered Template we want to register: templates = templates_service.list(unregistered=True) template = next( (t for t in templates if (t.id == module.params['id'] or t.name == module.params['name'])), None ) changed = False if template is None: template = templates_module.search_entity() if template is None: raise ValueError( "Template '%s(%s)' wasn't found." % (module.params['name'], module.params['id']) ) else: # Register the template into the system: changed = True template_service = templates_service.template_service(template.id) template_service.register( allow_partial_import=module.params['allow_partial_import'], cluster=otypes.Cluster( name=module.params['cluster'] ) if module.params['cluster'] else None, vnic_profile_mappings=_get_vnic_profile_mappings(module) if module.params['vnic_profile_mappings'] else None, registration_configuration=otypes.RegistrationConfiguration( cluster_mappings=_get_cluster_mappings(module), role_mappings=_get_role_mappings(module), domain_mappings=_get_domain_mappings(module), ) if (module.params['cluster_mappings'] or module.params['role_mappings'] or module.params['domain_mappings']) else None ) if module.params['wait']: template = templates_module.wait_for_import() else: # Fetch template to initialize return. template = template_service.get() ret = templates_module.create(result_state=otypes.TemplateStatus.OK) ret = { 'changed': changed, 'id': template.id, 'template': get_dict_of_struct(template) } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(default=None, aliases=['host'], required=True), bond=dict(default=None, type='dict'), interface=dict(default=None), networks=dict(default=None, type='list'), labels=dict(default=None, type='list'), check=dict(default=None, type='bool'), save=dict(default=None, type='bool'), ) module = AnsibleModule(argument_spec=argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() host_networks_module = HostNetworksModule( connection=connection, module=module, service=hosts_service, ) host = host_networks_module.search_entity() if host is None: raise Exception("Host '%s' was not found." % module.params['name']) bond = module.params['bond'] interface = module.params['interface'] networks = module.params['networks'] labels = module.params['labels'] nic_name = bond.get('name') if bond else module.params['interface'] nics_service = hosts_service.host_service(host.id).nics_service() nic = search_by_name(nics_service, nic_name) state = module.params['state'] if (state == 'present' and (nic is None or host_networks_module.has_update( nics_service.service(nic.id)))): host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module._action_save_configuration, check_connectivity=module.params['check'], modified_bonds=[ otypes.HostNic( name=bond.get('name'), bonding=otypes.Bonding( options=[ otypes.Option( name="mode", value=str(bond.get('mode')), ) ], slaves=[ otypes.HostNic(name=i) for i in bond.get('interfaces', []) ], ), ), ] if bond else None, modified_labels=[ otypes.NetworkLabel( id=str(name), host_nic=otypes.HostNic( name=bond.get('name') if bond else interface), ) for name in labels ] if labels else None, modified_network_attachments=[ otypes.NetworkAttachment( network=otypes.Network( name=network['name']) if network['name'] else None, host_nic=otypes.HostNic( name=bond.get('name') if bond else interface), ip_address_assignments=[ otypes.IpAddressAssignment( assignment_method=otypes.BootProtocol( network.get('boot_protocol', 'none')), ip=otypes.Ip( address=network.get('address'), gateway=network.get('gateway'), netmask=network.get('netmask'), version=otypes.IpVersion( network.get('version')) if network.get('version') else None, ), ), ], ) for network in networks ] if networks else None, ) elif state == 'absent' and nic: attachments_service = nics_service.nic_service( nic.id).network_attachments_service() attachments = attachments_service.list() if networks: network_names = [network['name'] for network in networks] attachments = [ attachment for attachment in attachments if get_link_name( connection, attachment.network) in network_names ] if labels or bond or attachments: host_networks_module.action( entity=host, action='setup_networks', post_action=host_networks_module. _action_save_configuration, check_connectivity=module.params['check'], removed_bonds=[ otypes.HostNic(name=bond.get('name'), ), ] if bond else None, removed_labels=[ otypes.NetworkLabel(name=str(name), ) for name in labels ] if labels else None, removed_network_attachments=list(attachments), ) nic = search_by_name(nics_service, nic_name) module.exit_json( **{ 'changed': host_networks_module.changed, 'id': nic.id if nic else None, 'host_nic': get_dict_of_struct(nic), }) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict(choices=['present', 'absent', 'attached', 'detached'], default='present'), id=dict(default=None), name=dict(default=None, aliases=['alias']), vm_name=dict(default=None), vm_id=dict(default=None), size=dict(default=None), interface=dict(default=None, ), storage_domain=dict(default=None), storage_domains=dict(default=None, type='list'), profile=dict(default=None), format=dict(default='cow', choices=['raw', 'cow']), bootable=dict(default=None, type='bool'), shareable=dict(default=None, type='bool'), logical_unit=dict(default=None, type='dict'), download_image_path=dict(default=None), upload_image_path=dict(default=None, aliases=['image_path']), force=dict(default=False, type='bool'), sparsify=dict(default=None, type='bool'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: disk = None state = module.params['state'] auth = module.params.get('auth') connection = create_connection(auth) disks_service = connection.system_service().disks_service() disks_module = DisksModule( connection=connection, module=module, service=disks_service, ) lun = module.params.get('logical_unit') if lun: disk = _search_by_lun(disks_service, lun.get('id')) ret = None # First take care of creating the VM, if needed: if state == 'present' or state == 'detached' or state == 'attached': ret = disks_module.create( entity=disk, result_state=otypes.DiskStatus.OK if lun is None else None, ) is_new_disk = ret['changed'] ret['changed'] = ret[ 'changed'] or disks_module.update_storage_domains(ret['id']) # We need to pass ID to the module, so in case we want detach/attach disk # we have this ID specified to attach/detach method: module.params['id'] = ret['id'] if disk is None else disk.id # Upload disk image in case it's new disk or force parameter is passed: if module.params['upload_image_path'] and (is_new_disk or module.params['force']): uploaded = upload_disk_image(connection, module) ret['changed'] = ret['changed'] or uploaded # Download disk image in case it's file don't exist or force parameter is passed: if (module.params['download_image_path'] and (not os.path.isfile(module.params['download_image_path']) or module.params['force'])): downloaded = download_disk_image(connection, module) ret['changed'] = ret['changed'] or downloaded # Disk sparsify, only if disk is of image type: disk = disks_service.disk_service(module.params['id']).get() if disk.storage_type == otypes.DiskStorageType.IMAGE: ret = disks_module.action( action='sparsify', action_condition=lambda d: module.params['sparsify'], wait_condition=lambda d: d.status == otypes.DiskStatus.OK, ) elif state == 'absent': ret = disks_module.remove() # If VM was passed attach/detach disks to/from the VM: if module.params.get('vm_id') is not None or module.params.get( 'vm_name') is not None and state != 'absent': vms_service = connection.system_service().vms_service() # If `vm_id` isn't specified, find VM by name: vm_id = module.params['vm_id'] if vm_id is None: vm_id = getattr( search_by_name(vms_service, module.params['vm_name']), 'id', None) if vm_id is None: module.fail_json( msg="VM don't exists, please create it first.") disk_attachments_service = vms_service.vm_service( vm_id).disk_attachments_service() disk_attachments_module = DiskAttachmentsModule( connection=connection, module=module, service=disk_attachments_service, changed=ret['changed'] if ret else False, ) if state == 'present' or state == 'attached': ret = disk_attachments_module.create() if lun is None: wait( service=disk_attachments_service.service(ret['id']), condition=lambda d: follow_link(connection, d.disk). status == otypes.DiskStatus.OK, wait=module.params['wait'], timeout=module.params['timeout'], ) elif state == 'detached': ret = disk_attachments_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'attached', 'detached', 'exported'], default='present' ), id=dict(default=None), name=dict(default=None, aliases=['alias']), description=dict(default=None), vm_name=dict(default=None), vm_id=dict(default=None), size=dict(default=None), interface=dict(default=None,), storage_domain=dict(default=None), storage_domains=dict(default=None, type='list'), profile=dict(default=None), quota_id=dict(default=None), format=dict(default='cow', choices=['raw', 'cow']), sparse=dict(default=None, type='bool'), bootable=dict(default=None, type='bool'), shareable=dict(default=None, type='bool'), logical_unit=dict(default=None, type='dict'), download_image_path=dict(default=None), upload_image_path=dict(default=None, aliases=['image_path']), force=dict(default=False, type='bool'), sparsify=dict(default=None, type='bool'), openstack_volume_type=dict(default=None), image_provider=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) if module._name == 'ovirt_disks': module.deprecate("The 'ovirt_disks' module is being renamed 'ovirt_disk'", version=2.8) check_sdk(module) check_params(module) try: disk = None state = module.params['state'] auth = module.params.get('auth') connection = create_connection(auth) disks_service = connection.system_service().disks_service() disks_module = DisksModule( connection=connection, module=module, service=disks_service, ) lun = module.params.get('logical_unit') if lun: disk = _search_by_lun(disks_service, lun.get('id')) ret = None # First take care of creating the VM, if needed: if state in ('present', 'detached', 'attached'): ret = disks_module.create( entity=disk, result_state=otypes.DiskStatus.OK if lun is None else None, fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL if lun is None else False, ) is_new_disk = ret['changed'] ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id']) # We need to pass ID to the module, so in case we want detach/attach disk # we have this ID specified to attach/detach method: module.params['id'] = ret['id'] if disk is None else disk.id # Upload disk image in case it's new disk or force parameter is passed: if module.params['upload_image_path'] and (is_new_disk or module.params['force']): uploaded = upload_disk_image(connection, module) ret['changed'] = ret['changed'] or uploaded # Download disk image in case it's file don't exist or force parameter is passed: if ( module.params['download_image_path'] and (not os.path.isfile(module.params['download_image_path']) or module.params['force']) ): downloaded = download_disk_image(connection, module) ret['changed'] = ret['changed'] or downloaded # Disk sparsify, only if disk is of image type: disk = disks_service.disk_service(module.params['id']).get() if disk.storage_type == otypes.DiskStorageType.IMAGE: ret = disks_module.action( action='sparsify', action_condition=lambda d: module.params['sparsify'], wait_condition=lambda d: d.status == otypes.DiskStatus.OK, ) # Export disk as image to glance domain elif state == 'exported': disk = disks_module.search_entity() if disk is None: module.fail_json( msg="Can not export given disk '%s', it doesn't exist" % module.params.get('name') or module.params.get('id') ) if disk.storage_type == otypes.DiskStorageType.IMAGE: ret = disks_module.action( action='export', action_condition=lambda d: module.params['image_provider'], wait_condition=lambda d: d.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain(name=module.params['image_provider']), ) elif state == 'absent': ret = disks_module.remove() # If VM was passed attach/detach disks to/from the VM: if module.params.get('vm_id') is not None or module.params.get('vm_name') is not None and state != 'absent': vms_service = connection.system_service().vms_service() # If `vm_id` isn't specified, find VM by name: vm_id = module.params['vm_id'] if vm_id is None: vm_id = getattr(search_by_name(vms_service, module.params['vm_name']), 'id', None) if vm_id is None: module.fail_json( msg="VM don't exists, please create it first." ) disk_attachments_service = vms_service.vm_service(vm_id).disk_attachments_service() disk_attachments_module = DiskAttachmentsModule( connection=connection, module=module, service=disk_attachments_service, changed=ret['changed'] if ret else False, ) if state == 'present' or state == 'attached': ret = disk_attachments_module.create() if lun is None: wait( service=disk_attachments_service.service(ret['id']), condition=lambda d: follow_link(connection, d.disk).status == otypes.DiskStatus.OK, wait=module.params['wait'], timeout=module.params['timeout'], ) elif state == 'detached': ret = disk_attachments_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), name=dict(default=None, required=True, aliases=['host']), address=dict(default=None), username=dict(default=None), password=dict(default=None), type=dict(default=None), port=dict(default=None, type='int'), slot=dict(default=None), options=dict(default=None, type='dict'), encrypt_options=dict(default=None, type='bool', aliases=['encrypt']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) hosts_service = connection.system_service().hosts_service() host = search_by_name(hosts_service, module.params['name']) fence_agents_service = hosts_service.host_service( host.id).fence_agents_service() host_pm_module = HostPmModule( connection=connection, module=module, service=fence_agents_service, ) host_module = HostModule( connection=connection, module=module, service=hosts_service, ) state = module.params['state'] if state == 'present': agent = host_pm_module.search_entity( search_params={ 'address': module.params['address'], 'type': module.params['type'], }) ret = host_pm_module.create(entity=agent) # Enable Power Management, if it's not enabled: host_module.create(entity=host) elif state == 'absent': agent = host_pm_module.search_entity( search_params={ 'address': module.params['address'], 'type': module.params['type'], }) ret = host_pm_module.remove(entity=agent) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent', 'attached', 'detached', 'exported', 'imported'], default='present' ), id=dict(default=None), name=dict(default=None, aliases=['alias']), description=dict(default=None), vm_name=dict(default=None), vm_id=dict(default=None), size=dict(default=None), interface=dict(default=None,), storage_domain=dict(default=None), storage_domains=dict(default=None, type='list'), profile=dict(default=None), quota_id=dict(default=None), format=dict(default='cow', choices=['raw', 'cow']), content_type=dict( default='data', choices=['data', 'iso', 'hosted_engine', 'hosted_engine_sanlock', 'hosted_engine_metadata', 'hosted_engine_configuration'] ), sparse=dict(default=None, type='bool'), bootable=dict(default=None, type='bool'), shareable=dict(default=None, type='bool'), logical_unit=dict(default=None, type='dict'), download_image_path=dict(default=None), upload_image_path=dict(default=None, aliases=['image_path']), force=dict(default=False, type='bool'), sparsify=dict(default=None, type='bool'), openstack_volume_type=dict(default=None), image_provider=dict(default=None), host=dict(default=None), wipe_after_delete=dict(type='bool', default=None), activate=dict(default=None, type='bool'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) lun = module.params.get('logical_unit') host = module.params['host'] # Fail when host is specified with the LUN id. Lun id is needed to identify # an existing disk if already available inthe environment. if (host and lun is None) or (host and lun.get("id") is None): module.fail_json( msg="Can not use parameter host ({0!s}) without " "specifying the logical_unit id".format(host) ) check_sdk(module) check_params(module) try: disk = None state = module.params['state'] auth = module.params.get('auth') connection = create_connection(auth) disks_service = connection.system_service().disks_service() disks_module = DisksModule( connection=connection, module=module, service=disks_service, ) force_create = False vm_service = get_vm_service(connection, module) if lun: disk = _search_by_lun(disks_service, lun.get('id')) else: disk = disks_module.search_entity(search_params=searchable_attributes(module)) if vm_service and disk: # If the VM don't exist in VMs disks, but still it's found it means it was found # for template with same name as VM, so we should force create the VM disk. force_create = disk.id not in [a.disk.id for a in vm_service.disk_attachments_service().list() if a.disk] ret = None # First take care of creating the VM, if needed: if state in ('present', 'detached', 'attached'): # Always activate disk when its being created if vm_service is not None and disk is None: module.params['activate'] = True ret = disks_module.create( entity=disk if not force_create else None, result_state=otypes.DiskStatus.OK if lun is None else None, fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL if lun is None else False, force_create=force_create, ) is_new_disk = ret['changed'] ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id']) # We need to pass ID to the module, so in case we want detach/attach disk # we have this ID specified to attach/detach method: module.params['id'] = ret['id'] # Upload disk image in case it's new disk or force parameter is passed: if module.params['upload_image_path'] and (is_new_disk or module.params['force']): uploaded = upload_disk_image(connection, module) ret['changed'] = ret['changed'] or uploaded # Download disk image in case it's file don't exist or force parameter is passed: if ( module.params['download_image_path'] and (not os.path.isfile(module.params['download_image_path']) or module.params['force']) ): downloaded = download_disk_image(connection, module) ret['changed'] = ret['changed'] or downloaded # Disk sparsify, only if disk is of image type: if not module.check_mode: disk = disks_service.disk_service(module.params['id']).get() if disk.storage_type == otypes.DiskStorageType.IMAGE: ret = disks_module.action( action='sparsify', action_condition=lambda d: module.params['sparsify'], wait_condition=lambda d: d.status == otypes.DiskStatus.OK, ) # Export disk as image to glance domain elif state == 'exported': disk = disks_module.search_entity() if disk is None: module.fail_json( msg="Can not export given disk '%s', it doesn't exist" % module.params.get('name') or module.params.get('id') ) if disk.storage_type == otypes.DiskStorageType.IMAGE: ret = disks_module.action( action='export', action_condition=lambda d: module.params['image_provider'], wait_condition=lambda d: d.status == otypes.DiskStatus.OK, storage_domain=otypes.StorageDomain(name=module.params['image_provider']), ) elif state == 'imported': glance_service = connection.system_service().openstack_image_providers_service() image_provider = search_by_name(glance_service, module.params['image_provider']) images_service = glance_service.service(image_provider.id).images_service() entity_id = get_id_by_name(images_service, module.params['name']) images_service.service(entity_id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain'] ) if module.params['storage_domain'] else None, disk=otypes.Disk( name=module.params['name'] ), import_as_template=False, ) # Wait for disk to appear in system: disk = disks_module.wait_for_import( condition=lambda t: t.status == otypes.DiskStatus.OK ) ret = disks_module.create(result_state=otypes.DiskStatus.OK) elif state == 'absent': ret = disks_module.remove() # If VM was passed attach/detach disks to/from the VM: if vm_service: disk_attachments_service = vm_service.disk_attachments_service() disk_attachments_module = DiskAttachmentsModule( connection=connection, module=module, service=disk_attachments_service, changed=ret['changed'] if ret else False, ) if state == 'present' or state == 'attached': ret = disk_attachments_module.create() if lun is None: wait( service=disk_attachments_service.service(ret['id']), condition=lambda d: follow_link(connection, d.disk).status == otypes.DiskStatus.OK, wait=module.params['wait'], timeout=module.params['timeout'], ) elif state == 'detached': ret = disk_attachments_module.remove() # When the host parameter is specified and the disk is not being # removed, refresh the information about the LUN. if state != 'absent' and host: hosts_service = connection.system_service().hosts_service() host_id = get_id_by_name(hosts_service, host) disks_service.disk_service(disk.id).refresh_lun(otypes.Host(id=host_id)) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=[ 'present', 'absent', 'exported', 'imported', 'registered' ], default='present', ), id=dict(default=None), name=dict(default=None), vm=dict(default=None), timezone=dict(type='str'), description=dict(default=None), sso=dict(type='bool'), ballooning_enabled=dict(type='bool', default=None), cluster=dict(default=None), usb_support=dict(type='bool'), allow_partial_import=dict(default=None, type='bool'), cpu_profile=dict(default=None), clone_permissions=dict(type='bool'), export_domain=dict(default=None), storage_domain=dict(default=None), exclusive=dict(type='bool'), clone_name=dict(default=None), image_provider=dict(default=None), soundcard_enabled=dict(type='bool', default=None), smartcard_enabled=dict(type='bool', default=None), image_disk=dict(default=None, aliases=['glance_image_disk_name']), io_threads=dict(type='int', default=None), template_image_disk_name=dict(default=None), version=dict(default=None, type='dict'), seal=dict(type='bool'), vnic_profile_mappings=dict(default=[], type='list'), cluster_mappings=dict(default=[], type='list'), role_mappings=dict(default=[], type='list'), domain_mappings=dict(default=[], type='list'), operating_system=dict(type='str'), memory=dict(type='str'), memory_guaranteed=dict(type='str'), memory_max=dict(type='str'), nics=dict(type='list', default=[]), cloud_init=dict(type='dict'), cloud_init_nics=dict(type='list', default=[]), sysprep=dict(type='dict'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_one_of=[['id', 'name']], ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) templates_service = connection.system_service().templates_service() templates_module = TemplatesModule( connection=connection, module=module, service=templates_service, ) entity = None if module.params['version'] is not None and module.params[ 'version'].get('number') is not None: entity = find_subversion_template(module, templates_service) state = module.params['state'] if state == 'present': force_create = False if entity is None and module.params['version'] is not None: force_create = True ret = templates_module.create( entity=entity, # When user want to create new template subversion, we must make sure # template is force created as it already exists, but new version should be created. force_create=force_create, result_state=otypes.TemplateStatus.OK, search_params=searchable_attributes(module), clone_permissions=module.params['clone_permissions'], seal=module.params['seal'], ) elif state == 'absent': ret = templates_module.remove(entity=entity) elif state == 'exported': template = templates_module.search_entity() if entity is not None: template = entity export_service = templates_module._get_export_domain_service() export_template = search_by_attributes( export_service.templates_service(), id=template.id) ret = templates_module.action( entity=template, action='export', action_condition=lambda t: export_template is None or module. params['exclusive'], wait_condition=lambda t: t is not None, post_action=templates_module.post_export_action, storage_domain=otypes.StorageDomain( id=export_service.get().id), exclusive=module.params['exclusive'], ) elif state == 'imported': template = templates_module.search_entity() if entity is not None: template = entity if template and module.params['clone_name'] is None: ret = templates_module.create( result_state=otypes.TemplateStatus.OK, ) else: kwargs = {} if module.params['image_provider']: kwargs.update( disk=otypes.Disk( name=module.params['template_image_disk_name'] or module.params['image_disk']), template=otypes.Template( name=module.params['name'] if module.params['clone_name'] is None else module.params['clone_name'], ), clone=True if module.params['clone_name'] is not None else False, import_as_template=True, ) if module.params['image_disk']: # We need to refresh storage domain to get list of images: templates_module._get_export_domain_service( ).images_service().list() glance_service = connection.system_service( ).openstack_image_providers_service() image_provider = search_by_name( glance_service, module.params['image_provider']) images_service = glance_service.service( image_provider.id).images_service() else: images_service = templates_module._get_export_domain_service( ).templates_service() template_name = module.params['image_disk'] or module.params[ 'name'] entity = search_by_name(images_service, template_name) if entity is None: raise Exception("Image/template '%s' was not found." % template_name) images_service.service(entity.id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain']) if module.params['storage_domain'] else None, cluster=otypes.Cluster(name=module.params['cluster']) if module.params['cluster'] else None, **kwargs) # Wait for template to appear in system: template = templates_module.wait_for_import( condition=lambda t: t.status == otypes.TemplateStatus.OK) ret = templates_module.create( result_state=otypes.TemplateStatus.OK) ret = { 'changed': True, 'id': template.id, 'template': get_dict_of_struct(template), } elif state == 'registered': storage_domains_service = connection.system_service( ).storage_domains_service() # Find the storage domain with unregistered template: sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain']) storage_domain_service = storage_domains_service.storage_domain_service( sd_id) templates_service = storage_domain_service.templates_service() # Find the unregistered Template we want to register: templates = templates_service.list(unregistered=True) template = next( (t for t in templates if (t.id == module.params['id'] or t.name == module.params['name'])), None) changed = False if template is None: template = templates_module.search_entity() if template is None: raise ValueError( "Template '%s(%s)' wasn't found." % (module.params['name'], module.params['id'])) else: # Register the template into the system: changed = True template_service = templates_service.template_service( template.id) template_service.register( allow_partial_import=module.params['allow_partial_import'], cluster=otypes.Cluster(name=module.params['cluster']) if module.params['cluster'] else None, vnic_profile_mappings=_get_vnic_profile_mappings(module) if module.params['vnic_profile_mappings'] else None, registration_configuration=otypes. RegistrationConfiguration( cluster_mappings=_get_cluster_mappings(module), role_mappings=_get_role_mappings(module), domain_mappings=_get_domain_mappings(module), ) if (module.params['cluster_mappings'] or module.params['role_mappings'] or module.params['domain_mappings']) else None) if module.params['wait']: template = templates_module.wait_for_import() else: # Fetch template to initialize return. template = template_service.get() ret = templates_module.create( result_state=otypes.TemplateStatus.OK) ret = { 'changed': changed, 'id': template.id, 'template': get_dict_of_struct(template) } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def _get_obj_id(obj_service, obj_name): obj = search_by_name(obj_service, obj_name) if obj is None: raise Exception("Object '%s' was not found." % obj_name) return obj.id
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=[ 'present', 'absent', 'exported', 'imported', 'registered' ], default='present', ), name=dict(default=None, required=True), vm=dict(default=None), description=dict(default=None), cluster=dict(default=None), cpu_profile=dict(default=None), disks=dict(default=[], type='list'), clone_permissions=dict(type='bool'), export_domain=dict(default=None), storage_domain=dict(default=None), exclusive=dict(type='bool'), image_provider=dict(default=None), image_disk=dict(default=None, aliases=['glance_image_disk_name']), template_image_disk_name=dict(default=None), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) templates_service = connection.system_service().templates_service() templates_module = TemplatesModule( connection=connection, module=module, service=templates_service, ) state = module.params['state'] if state == 'present': ret = templates_module.create( result_state=otypes.TemplateStatus.OK, clone_permissions=module.params['clone_permissions'], ) elif state == 'absent': ret = templates_module.remove() elif state == 'exported': template = templates_module.search_entity() export_service = templates_module._get_export_domain_service() export_template = search_by_attributes( export_service.templates_service(), id=template.id) ret = templates_module.action( entity=template, action='export', action_condition=lambda t: export_template is None, wait_condition=lambda t: t is not None, post_action=templates_module.post_export_action, storage_domain=otypes.StorageDomain( id=export_service.get().id), exclusive=module.params['exclusive'], ) elif state == 'imported': template = templates_module.search_entity() if template: ret = templates_module.create( result_state=otypes.TemplateStatus.OK, ) else: kwargs = {} if module.params['image_provider']: kwargs.update( disk=otypes.Disk( name=module.params['template_image_disk_name'] or module.params['image_disk']), template=otypes.Template(name=module.params['name'], ), import_as_template=True, ) if module.params['image_disk']: # We need to refresh storage domain to get list of images: templates_module._get_export_domain_service( ).images_service().list() glance_service = connection.system_service( ).openstack_image_providers_service() image_provider = search_by_name( glance_service, module.params['image_provider']) images_service = glance_service.service( image_provider.id).images_service() else: images_service = templates_module._get_export_domain_service( ).templates_service() template_name = module.params['image_disk'] or module.params[ 'name'] entity = search_by_name(images_service, template_name) if entity is None: raise Exception("Image/template '%s' was not found." % template_name) images_service.service(entity.id).import_( storage_domain=otypes.StorageDomain( name=module.params['storage_domain']) if module.params['storage_domain'] else None, cluster=otypes.Cluster(name=module.params['cluster']) if module.params['cluster'] else None, **kwargs) template = wait_for_import(module, templates_service) ret = { 'changed': True, 'id': template.id, 'template': get_dict_of_struct(template), } elif state == 'registered': storage_domains_service = connection.system_service( ).storage_domains_service() # Find the storage domain with unregistered template: sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain']) storage_domain_service = storage_domains_service.storage_domain_service( sd_id) templates_service = storage_domain_service.templates_service() # Find the unregistered Template we want to register: templates = templates_service.list(unregistered=True) template = next( (t for t in templates if t.name == module.params['name']), None) changed = False if template is None: # Test if template is registered: template = templates_module.search_entity() if template is None: raise ValueError("Template with name '%s' wasn't found." % module.params['name']) else: changed = True template_service = templates_service.template_service( template.id) # Register the template into the system: template_service.register( cluster=otypes.Cluster(name=module.params['cluster']) if module.params['cluster'] else None, template=otypes.Template(name=module.params['name'], ), ) if module.params['wait']: template = wait_for_import(module, templates_service) ret = { 'changed': changed, 'id': template.id, 'template': get_dict_of_struct(template) } module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), cluster=dict(default=None, required=True), name=dict(default=None, required=True), description=dict(default=None), vm_enforcing=dict(default=None, type='bool'), vm_rule=dict(default=None, choices=['positive', 'negative', 'disabled']), host_enforcing=dict(default=None, type='bool'), host_rule=dict(default=None, choices=['positive', 'negative']), vms=dict(default=None, type='list'), hosts=dict(default=None, type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) if module._name == 'ovirt_affinity_groups': module.deprecate("The 'ovirt_affinity_groups' module is being renamed 'ovirt_affinity_group'", version=2.8) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) # Check if unsupported parameters were passed: supported_41 = ('host_enforcing', 'host_rule', 'hosts') if not check_support( version='4.1', connection=connection, module=module, params=supported_41, ): module.fail_json( msg='Following parameters are supported since 4.1: {params}'.format( params=supported_41, ) ) clusters_service = connection.system_service().clusters_service() vms_service = connection.system_service().vms_service() hosts_service = connection.system_service().hosts_service() cluster_name = module.params['cluster'] cluster = search_by_name(clusters_service, cluster_name) if cluster is None: raise Exception("Cluster '%s' was not found." % cluster_name) cluster_service = clusters_service.cluster_service(cluster.id) affinity_groups_service = cluster_service.affinity_groups_service() # Fetch VM ids which should be assigned to affinity group: vm_ids = sorted([ get_id_by_name(vms_service, vm_name) for vm_name in module.params['vms'] ]) if module.params['vms'] is not None else None # Fetch host ids which should be assigned to affinity group: host_ids = sorted([ get_id_by_name(hosts_service, host_name) for host_name in module.params['hosts'] ]) if module.params['hosts'] is not None else None affinity_groups_module = AffinityGroupsModule( connection=connection, module=module, service=affinity_groups_service, vm_ids=vm_ids, host_ids=host_ids, ) state = module.params['state'] if state == 'present': ret = affinity_groups_module.create() elif state == 'absent': ret = affinity_groups_module.remove() module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)