def _update_tag_assignments(self, entity, name): if self._module.params[name] is None: return state = self.param('state') 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: if state in ['present', 'attached', 'detached']: for entity_name in self._module.params[name]: entity_id = get_id_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 state in ['attached', 'present']: 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 # Detach the tag: elif state == 'detached': if self._module.params['name'] in current_tags: tag_id = get_id_by_name(tags_service, self.param('name')) if not self._module.check_mode: tags_service.tag_service(tag_id).remove() self.changed = True # Unassign tags: if state == 'present': 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_id = get_id_by_name(entities_service, entity_name) tags_service = entities_service.service( entity_id).tags_service() tag_id = get_id_by_name(tags_service, self.param('name')) tags_service.tag_service(tag_id).remove() self.changed = True
def build_entity(self): if self.param('external_provider'): ons_service = self._connection.system_service( ).openstack_network_providers_service() on_service = ons_service.provider_service( get_id_by_name(ons_service, self.param('external_provider'))) return otypes.Network( name=self._module.params['name'], comment=self._module.params['comment'], description=self._module.params['description'], id=self._module.params['id'], data_center=otypes.DataCenter( name=self._module.params['data_center'], ) if self._module.params['data_center'] else None, vlan=otypes.Vlan(self._module.params['vlan_tag'], ) if self._module.params['vlan_tag'] else None, usages=[ otypes.NetworkUsage.VM if self._module.params['vm_network'] else None ] if self._module.params['vm_network'] is not None else None, mtu=self._module.params['mtu'], external_provider=otypes.OpenStackNetworkProvider( id=on_service.get().id) if self.param('external_provider') else None, )
def _get_qos_id(self): if self.param('qos'): qoss_service = self._get_dcs_service().service( self._get_dcs_id()).qoss_service() return get_id_by_name( qoss_service, self.param('qos')) if self.param('qos') else None return None
def build_entity(self): hosts_service = self._connection.system_service().hosts_service() logical_unit = self._module.params.get('logical_unit') size = convert_to_bytes(self._module.params.get('size')) if not size and self._module.params.get('upload_image_path'): size = os.path.getsize(self._module.params.get('upload_image_path')) disk = otypes.Disk( id=self._module.params.get('id'), name=self._module.params.get('name'), description=self._module.params.get('description'), format=otypes.DiskFormat( self._module.params.get('format') ) if self._module.params.get('format') else None, content_type=otypes.DiskContentType( self._module.params.get('content_type') ) if self._module.params.get('content_type') else None, sparse=self._module.params.get( 'sparse' ) if self._module.params.get( 'sparse' ) is not None else self._module.params.get('format') != 'raw', openstack_volume_type=otypes.OpenStackVolumeType( name=self.param('openstack_volume_type') ) if self.param('openstack_volume_type') else None, provisioned_size=size, storage_domains=[ otypes.StorageDomain( name=self._module.params.get('storage_domain'), ), ], quota=otypes.Quota(id=self._module.params.get('quota_id')) if self.param('quota_id') else None, shareable=self._module.params.get('shareable'), sgio=otypes.ScsiGenericIO(self.param('scsi_passthrough')) if self.param('scsi_passthrough') else None, propagate_errors=self.param('propagate_errors'), backup=otypes.DiskBackup(self.param('backup')) if self.param('backup') else None, wipe_after_delete=self.param('wipe_after_delete'), lun_storage=otypes.HostStorage( host=otypes.Host( id=get_id_by_name(hosts_service, self._module.params.get('host')) ) if self.param('host') else None, type=otypes.StorageType( logical_unit.get('storage_type', 'iscsi') ), logical_units=[ otypes.LogicalUnit( address=logical_unit.get('address'), port=logical_unit.get('port', 3260), target=logical_unit.get('target'), id=logical_unit.get('id'), username=logical_unit.get('username'), password=logical_unit.get('password'), ) ], ) if logical_unit else None, ) if hasattr(disk, 'initial_size') and self._module.params['upload_image_path']: disk.initial_size = size return disk
def main(): argument_spec = ovirt_info_full_argument_spec( host=dict(required=True), iscsi=dict(default=None, type='dict'), fcp=dict(default=None, type='dict'), ) module = AnsibleModule(argument_spec) is_old_facts = module._name in ('ovirt_host_storage_facts', 'community.general.ovirt_host_storage_facts') if is_old_facts: module.deprecate("The 'ovirt_host_storage_facts' module has been renamed to 'ovirt_host_storage_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) # Get Host hosts_service = connection.system_service().hosts_service() host_id = get_id_by_name(hosts_service, module.params['host']) storage_type = _get_storage_type(module.params) host_service = hosts_service.host_service(host_id) if storage_type == 'iscsi': # Login iscsi = module.params.get('iscsi') _login(host_service, iscsi) # Get LUNs exposed from the specified target host_storages = host_service.storage_service().list() if storage_type == 'iscsi': filterred_host_storages = [host_storage for host_storage in host_storages if host_storage.type == otypes.StorageType.ISCSI] if 'target' in iscsi: filterred_host_storages = [host_storage for host_storage in filterred_host_storages if iscsi.get('target') == host_storage.logical_units[0].target] elif storage_type == 'fcp': filterred_host_storages = [host_storage for host_storage in host_storages if host_storage.type == otypes.StorageType.FCP] result = dict( ovirt_host_storages=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in filterred_host_storages ], ) 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 get_snapshot_disk_id(module, snapshots_service): snapshot_service = snapshots_service.snapshot_service( module.params.get('snapshot_id')) snapshot_disks_service = snapshot_service.disks_service() disk_id = '' if module.params.get('disk_id'): disk_id = module.params.get('disk_id') elif module.params.get('disk_name'): disk_id = get_id_by_name(snapshot_disks_service, module.params.get('disk_name')) return disk_id
def main(): argument_spec = ovirt_info_full_argument_spec( host=dict(required=True), iscsi=dict(default=None, type='dict'), fcp=dict(default=None, type='dict'), ) module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) # Get Host hosts_service = connection.system_service().hosts_service() host_id = get_id_by_name(hosts_service, module.params['host']) host_service = hosts_service.host_service(host_id) if module.params.get('iscsi'): # Login _login(host_service, module.params.get('iscsi')) # Get LUNs exposed from the specified target host_storages = host_service.storage_service().list() if module.params.get('iscsi') is not None: host_storages = list( filter(lambda x: x.type == otypes.StorageType.ISCSI, host_storages)) if 'target' in module.params.get('iscsi'): host_storages = list( filter( lambda x: module.params.get('iscsi').get('target') == x .logical_units[0].target, host_storages)) elif module.params.get('fcp') is not None: host_storages = list( filter(lambda x: x.type == otypes.StorageType.FCP, host_storages)) result = dict(ovirt_host_storages=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in host_storages ], ) 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_info_full_argument_spec( storage_domain=dict(default=None), max=dict(default=None, type='int'), unregistered=dict(default=False, type='bool'), ) module = AnsibleModule(argument_spec) is_old_facts = module._name in ( 'ovirt_storage_template_facts', 'community.general.ovirt_storage_template_facts') if is_old_facts: module.deprecate( "The 'ovirt_storage_template_facts' module has been renamed to 'ovirt_storage_template_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) storage_domains_service = connection.system_service( ).storage_domains_service() 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: if module.params.get('unregistered'): templates = templates_service.list(unregistered=True) else: templates = templates_service.list(max=module.params['max']) result = dict(ovirt_storage_templates=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in templates ], ) 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 get_vm_service(connection, module): if module.params.get('vm_id') is not None or module.params.get( 'vm_name') is not None and module.params['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 = get_id_by_name(vms_service, module.params['vm_name']) if vm_id is None: module.fail_json(msg="VM don't exists, please create it first.") return vms_service.vm_service(vm_id)
def get_storage_connections(iscsi_bond, connection): resp = [] for storage_domain_name in iscsi_bond.get('storage_domains', []): storage_domains_service = connection.system_service( ).storage_domains_service() storage_domain = storage_domains_service.storage_domain_service( get_id_by_name(storage_domains_service, storage_domain_name)).get() resp.extend(connection.follow_link(storage_domain.storage_connections)) for storage_connection_id in iscsi_bond.get('storage_connections', []): resp.append(connection.system_service().storage_connections_service(). storage_connection_service(storage_connection_id).get()) return resp
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 if disk.content_type in [ otypes.DiskContentType(x) for x in [ 'hosted_engine', 'hosted_engine_sanlock', 'hosted_engine_metadata', 'hosted_engine_configuration' ] ]: 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']) if new_disk_storage_id in [sd.id for sd in disk.storage_domains]: return changed 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 _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 main(): argument_spec = ovirt_info_full_argument_spec( storage_domain=dict(default=None), max=dict(default=None, type='int'), unregistered=dict(default=False, type='bool'), ) module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) storage_domains_service = connection.system_service( ).storage_domains_service() sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain']) storage_domain_service = storage_domains_service.storage_domain_service( sd_id) vms_service = storage_domain_service.vms_service() # Find the unregistered VM we want to register: if module.params.get('unregistered'): vms = vms_service.list(unregistered=True) else: vms = vms_service.list() result = dict(ovirt_storage_vms=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in vms ], ) 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 _login(self, storage_type, storage): if storage_type == 'iscsi': hosts_service = self._connection.system_service().hosts_service() host_id = get_id_by_name(hosts_service, self.param('host')) if storage.get('target'): 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'), ), ) elif storage.get('target_lun_map'): for target in [ m['target'] for m in storage.get('target_lun_map') ]: hosts_service.host_service(host_id).iscsi_login( iscsi=otypes.IscsiDetails( username=storage.get('username'), password=storage.get('password'), address=storage.get('address'), target=target, ), )
def _get_external_network_provider_id(self, external_provider): return external_provider.get('id') or get_id_by_name( self._connection.system_service( ).openstack_network_providers_service(), external_provider.get('name'))
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', elements='dict'), cluster_mappings=dict(default=[], type='list', elements='dict'), role_mappings=dict(default=[], type='list', elements='dict'), domain_mappings=dict(default=[], type='list', elements='dict'), operating_system=dict(type='str'), memory=dict(type='str'), memory_guaranteed=dict(type='str'), memory_max=dict(type='str'), nics=dict(type='list', default=[], elements='dict'), cloud_init=dict(type='dict'), cloud_init_nics=dict(type='list', default=[], elements='dict'), 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 ) if template is None: raise TimeoutError("Image/template '%s' could not be imported. Try again with larger timeout." % template_name) ret = templates_module.create(result_state=otypes.TemplateStatus.OK) 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_network_filter_id(self): nf_service = self._connection.system_service().network_filters_service() return get_id_by_name(nf_service, self.param('network_filter')) if self.param('network_filter') else None
def _get_network_id(self): networks_service = self._get_dcs_service().service(self._get_dcs_id()).networks_service() return get_id_by_name(networks_service, self.param('network'))
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, _wait=True if module.params['upload_image_path'] else module.params['wait'], ) 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']): if module.params['format'] == 'cow' and module.params[ 'content_type'] == 'iso': module.warn( "To upload an ISO image 'format' parameter needs to be set to 'raw'." ) 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(type='str', default='present', choices=['absent', 'present']), cluster=dict(type='str', required=True), name=dict(type='str', required=True), description=dict(type='str'), vm_enforcing=dict(type='bool'), vm_rule=dict(type='str', choices=['disabled', 'negative', 'positive']), host_enforcing=dict(type='bool'), host_rule=dict(type='str', choices=['disabled', 'negative', 'positive']), vms=dict(type='list'), hosts=dict(type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) 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 build_entity(self): hosts_service = self._connection.system_service().hosts_service() logical_unit = self._module.params.get('logical_unit') size = convert_to_bytes(self._module.params.get('size')) if not size and self._module.params.get('upload_image_path'): out = subprocess.check_output([ "qemu-img", "info", "--output", "json", self._module.params.get('upload_image_path') ]) image_info = json.loads(out) size = image_info["virtual-size"] disk = otypes.Disk( id=self._module.params.get('id'), name=self._module.params.get('name'), description=self._module.params.get('description'), format=otypes.DiskFormat(self._module.params.get('format')) if self._module.params.get('format') else None, content_type=otypes.DiskContentType( self._module.params.get('content_type')) if self._module.params.get('content_type') else None, sparse=self._module.params.get('sparse') if self._module.params.get('sparse') is not None else self._module.params.get('format') != 'raw', openstack_volume_type=otypes.OpenStackVolumeType( name=self.param('openstack_volume_type')) if self.param('openstack_volume_type') else None, provisioned_size=size, storage_domains=[ otypes.StorageDomain( name=self._module.params.get('storage_domain'), ), ], quota=otypes.Quota(id=self._module.params.get('quota_id')) if self.param('quota_id') else None, shareable=self._module.params.get('shareable'), sgio=otypes.ScsiGenericIO(self.param('scsi_passthrough')) if self.param('scsi_passthrough') else None, propagate_errors=self.param('propagate_errors'), backup=otypes.DiskBackup(self.param('backup')) if self.param('backup') else None, wipe_after_delete=self.param('wipe_after_delete'), lun_storage=otypes.HostStorage( host=otypes.Host(id=get_id_by_name( hosts_service, self._module.params.get('host'))) if self.param('host') else None, type=otypes.StorageType( logical_unit.get('storage_type', 'iscsi')), logical_units=[ otypes.LogicalUnit( address=logical_unit.get('address'), port=logical_unit.get('port', 3260), target=logical_unit.get('target'), id=logical_unit.get('id'), username=logical_unit.get('username'), password=logical_unit.get('password'), ) ], ) if logical_unit else None, ) if hasattr( disk, 'initial_size') and self._module.params['upload_image_path']: out = subprocess.check_output([ 'qemu-img', 'measure', '-O', 'qcow2' if self._module.params.get('format') == 'cow' else 'raw', '--output', 'json', self._module.params['upload_image_path'] ]) measure = json.loads(out) disk.initial_size = measure["required"] return disk
def build_entity(self): sched_policy = self._get_sched_policy() return otypes.Cluster( id=self.param('id'), name=self.param('name'), comment=self.param('comment'), description=self.param('description'), ballooning_enabled=self.param('ballooning'), gluster_service=self.param('gluster'), virt_service=self.param('virt'), threads_as_cores=self.param('threads_as_cores'), ha_reservation=self.param('ha_reservation'), trusted_service=self.param('trusted_service'), optional_reason=self.param('vm_reason'), maintenance_reason_required=self.param('host_reason'), scheduling_policy=otypes.SchedulingPolicy(id=sched_policy.id, ) if sched_policy else None, serial_number=otypes.SerialNumber( policy=otypes.SerialNumberPolicy(self.param('serial_policy')), value=self.param('serial_policy_value'), ) if (self.param('serial_policy') is not None or self.param('serial_policy_value') is not None) else None, migration=otypes.MigrationOptions( auto_converge=otypes.InheritableBoolean( self.param('migration_auto_converge'), ) if self.param('migration_auto_converge') else None, bandwidth=otypes.MigrationBandwidth( assignment_method=otypes. MigrationBandwidthAssignmentMethod( self.param('migration_bandwidth'), ) if self.param('migration_bandwidth') else None, custom_value=self.param('migration_bandwidth_limit'), ) if (self.param('migration_bandwidth') or self.param('migration_bandwidth_limit')) else None, compressed=otypes.InheritableBoolean( self.param('migration_compressed'), ) if self.param('migration_compressed') else None, encrypted=otypes.InheritableBoolean( self.param('migration_encrypted'), ) if self.param('migration_encrypted') else None, policy=otypes.MigrationPolicy(id=self._get_policy_id()) if self.param('migration_policy') else None, ) if (self.param('migration_bandwidth') is not None or self.param('migration_bandwidth_limit') is not None or self.param('migration_auto_converge') is not None or self.param('migration_compressed') is not None or self.param('migration_encrypted') is not None or self.param('migration_policy') is not None) else None, error_handling=otypes.ErrorHandling(on_error=otypes.MigrateOnError( self.param('resilience_policy')), ) if self.param('resilience_policy') else None, fencing_policy=otypes.FencingPolicy( enabled=self.param('fence_enabled'), skip_if_gluster_bricks_up=self.param( 'fence_skip_if_gluster_bricks_up'), skip_if_gluster_quorum_not_met=self.param( 'fence_skip_if_gluster_quorum_not_met'), skip_if_connectivity_broken=otypes.SkipIfConnectivityBroken( enabled=self.param('fence_skip_if_connectivity_broken'), threshold=self.param('fence_connectivity_threshold'), ) if (self.param('fence_skip_if_connectivity_broken') is not None or self.param('fence_connectivity_threshold') is not None) else None, skip_if_sd_active=otypes.SkipIfSdActive( enabled=self.param('fence_skip_if_sd_active'), ) if self.param('fence_skip_if_sd_active') is not None else None, ) if (self.param('fence_enabled') is not None or self.param('fence_skip_if_sd_active') is not None or self.param('fence_skip_if_connectivity_broken') is not None or self.param('fence_skip_if_gluster_bricks_up') is not None or self.param('fence_skip_if_gluster_quorum_not_met') is not None or self.param('fence_connectivity_threshold') is not None) else None, display=otypes.Display(proxy=self.param('spice_proxy'), ) if self.param('spice_proxy') else None, required_rng_sources=[ otypes.RngSource(rng) for rng in self.param('rng_sources') ] if self.param('rng_sources') else None, memory_policy=otypes.MemoryPolicy( over_commit=otypes.MemoryOverCommit( percent=self._get_memory_policy(), ), ) if self.param('memory_policy') else None, ksm=otypes.Ksm( enabled=self.param('ksm'), merge_across_nodes=not self.param('ksm_numa'), ) if (self.param('ksm_numa') is not None or self.param('ksm') is not None) else None, data_center=otypes.DataCenter(name=self.param('data_center'), ) if self.param('data_center') else None, management_network=otypes.Network(name=self.param('network'), ) if self.param('network') else None, cpu=otypes.Cpu( architecture=otypes.Architecture(self.param('cpu_arch')) if self.param('cpu_arch') else None, type=self.param('cpu_type'), ) if (self.param('cpu_arch') or self.param('cpu_type')) else None, version=otypes.Version( major=self.__get_major(self.param('compatibility_version')), minor=self.__get_minor(self.param('compatibility_version')), ) if self.param('compatibility_version') else None, switch_type=otypes.SwitchType(self.param('switch_type')) if self.param('switch_type') else None, mac_pool=otypes.MacPool(id=get_id_by_name( self._connection.system_service().mac_pools_service(), self.param('mac_pool'))) if self.param('mac_pool') else None, external_network_providers=self. _get_external_network_providers_entity(), custom_scheduling_policy_properties=[ otypes.Property( name=sp.get('name'), value=str(sp.get('value')), ) for sp in self.param('scheduling_policy_properties') if sp ] if self.param('scheduling_policy_properties') is not None else None, firewall_type=otypes.FirewallType(self.param('firewall_type')) if self.param('firewall_type') else None, gluster_tuned_profile=self.param('gluster_tuned_profile'), )
def update_check(self, entity): sched_policy = self._get_sched_policy() migration_policy = getattr(entity.migration, 'policy', None) cluster_cpu = getattr(entity, 'cpu', dict()) def check_custom_scheduling_policy_properties(): if self.param('scheduling_policy_properties'): current = [] if entity.custom_scheduling_policy_properties: current = [ (sp.name, str(sp.value)) for sp in entity.custom_scheduling_policy_properties ] passed = [(sp.get('name'), str(sp.get('value'))) for sp in self.param('scheduling_policy_properties') if sp] for p in passed: if p not in current: return False return True return (check_custom_scheduling_policy_properties() and equal(self.param('name'), entity.name) and equal(self.param('comment'), entity.comment) and equal(self.param('description'), entity.description) and equal(self.param('switch_type'), str(entity.switch_type)) and equal(self.param('cpu_arch'), str(getattr(cluster_cpu, 'architecture', None))) and equal(self.param('cpu_type'), getattr(cluster_cpu, 'type', None)) and equal(self.param('ballooning'), entity.ballooning_enabled) and equal(self.param('gluster'), entity.gluster_service) and equal(self.param('virt'), entity.virt_service) and equal( self.param('threads_as_cores'), entity.threads_as_cores) and equal(self.param('ksm_numa'), not entity.ksm.merge_across_nodes) and equal(self.param('ksm'), entity.ksm.enabled) and equal(self.param('ha_reservation'), entity.ha_reservation) and equal(self.param('trusted_service'), entity.trusted_service) and equal(self.param('host_reason'), entity.maintenance_reason_required) and equal(self.param('vm_reason'), entity.optional_reason) and equal(self.param('spice_proxy'), getattr(entity.display, 'proxy', None)) and equal(self.param('fence_enabled'), entity.fencing_policy.enabled) and equal(self.param('fence_skip_if_gluster_bricks_up'), entity.fencing_policy.skip_if_gluster_bricks_up) and equal(self.param('fence_skip_if_gluster_quorum_not_met'), entity.fencing_policy.skip_if_gluster_quorum_not_met) and equal(self.param('fence_skip_if_sd_active'), entity.fencing_policy.skip_if_sd_active.enabled) and equal( self.param('fence_skip_if_connectivity_broken'), entity.fencing_policy.skip_if_connectivity_broken.enabled) and equal( self.param('fence_connectivity_threshold'), entity. fencing_policy.skip_if_connectivity_broken.threshold) and equal(self.param('resilience_policy'), str(entity.error_handling.on_error)) and equal(self.param('migration_bandwidth'), str(entity.migration.bandwidth.assignment_method)) and equal(self.param('migration_auto_converge'), str(entity.migration.auto_converge)) and equal(self.param('migration_compressed'), str(entity.migration.compressed)) and equal(self.param('migration_encrypted'), str(entity.migration.encrypted)) and equal(self.param('serial_policy'), str(getattr(entity.serial_number, 'policy', None))) and equal(self.param('serial_policy_value'), getattr(entity.serial_number, 'value', None)) and equal( self.param('scheduling_policy'), getattr( self._connection.follow_link(entity.scheduling_policy), 'name', None)) and equal(self.param('firewall_type'), str(entity.firewall_type)) and equal(self.param('gluster_tuned_profile'), getattr(entity, 'gluster_tuned_profile', None)) and equal(self._get_policy_id(), getattr(migration_policy, 'id', None)) and equal(self._get_memory_policy(), entity.memory_policy.over_commit.percent) and equal( self.__get_minor(self.param('compatibility_version')), self.__get_minor(entity.version)) and equal( self.__get_major(self.param('compatibility_version')), self.__get_major(entity.version)) and equal( self.param('migration_bandwidth_limit') if self.param('migration_bandwidth') == 'custom' else None, entity.migration.bandwidth.custom_value) and equal( sorted(self.param('rng_sources')) if self.param('rng_sources') else None, sorted([ str(source) for source in entity.required_rng_sources ])) and equal( get_id_by_name( self._connection.system_service().mac_pools_service(), self.param('mac_pool'), raise_error=False), entity.mac_pool.id) and self._update_check_external_network_providers(entity))
def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=[ 'present', 'absent', 'maintenance', 'upgraded', 'started', 'restarted', 'stopped', 'reinstalled', 'iscsidiscover', 'iscsilogin' ], default='present', ), name=dict(required=True), id=dict(default=None), comment=dict(default=None), cluster=dict(default=None), address=dict(default=None), ssh_port=dict(default=None, type='int'), password=dict(default=None, no_log=True), public_key=dict(default=False, type='bool', aliases=['ssh_public_key']), kdump_integration=dict(default=None, choices=['enabled', 'disabled']), spm_priority=dict(default=None, type='int'), override_iptables=dict(default=None, type='bool'), force=dict(default=False, type='bool'), timeout=dict(default=600, type='int'), override_display=dict(default=None), kernel_params=dict(default=None, type='list', elements='dict'), hosted_engine=dict(default=None, choices=['deploy', 'undeploy']), power_management_enabled=dict(default=None, type='bool'), activate=dict(default=True, type='bool'), iscsi=dict(default=None, type='dict'), check_upgrade=dict(default=True, type='bool'), reboot_after_upgrade=dict(default=True, type='bool'), vgpu_placement=dict(default=None, choices=['consolidated', 'separated']), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_if=[['state', 'iscsidiscover', ['iscsi']], ['state', 'iscsilogin', ['iscsi']]]) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) hosts_service = connection.system_service().hosts_service() start_event = connection.system_service().events_service().list( max=1)[0] hosts_module = HostsModule( connection=connection, module=module, service=hosts_service, start_event=start_event, ) state = module.params['state'] host = control_state(hosts_module) if state == 'present': ret = hosts_module.create( deploy_hosted_engine=(module.params.get('hosted_engine') == 'deploy') if module.params.get('hosted_engine') is not None else None, activate=module.params['activate'], result_state=( hoststate.MAINTENANCE if module.params['activate'] is False else hoststate.UP) if host is None else None, fail_condition=hosts_module.failed_state_after_reinstall if host is None else lambda h: False, ) if module.params['activate'] and host is not None: ret = hosts_module.action( action='activate', action_condition=lambda h: h.status != hoststate.UP, wait_condition=lambda h: h.status == hoststate.UP, fail_condition=failed_state, ) elif state == 'absent': ret = hosts_module.remove() elif state == 'maintenance': hosts_module.action( action='deactivate', action_condition=lambda h: h.status != hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.MAINTENANCE, fail_condition=failed_state, ) ret = hosts_module.create() elif state == 'upgraded': result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP events_service = connection.system_service().events_service() last_event = events_service.list(max=1)[0] if module.params['check_upgrade']: hosts_module.action( action='upgrade_check', action_condition=lambda host: not host.update_available, wait_condition=lambda host: host.update_available or (len([ event for event in events_service.list( from_=int(last_event.id), search='type=885', # Uncomment when 4.1 is EOL, and remove the cond: # if host.name in event.description # search='type=885 and host.name=%s' % host.name, ) if host.name in event.description ]) > 0), fail_condition=lambda host: len( events_service.list( from_=int(last_event.id), search='type=839 or type=887 and host.name=%s' % host.name, )) > 0, ) # Set to False, because upgrade_check isn't 'changing' action: hosts_module._changed = False ret = hosts_module.action( action='upgrade', action_condition=lambda h: h.update_available, wait_condition=lambda h: h.status == result_state, post_action=lambda h: time.sleep(module.params['poll_interval'] ), fail_condition=lambda h: hosts_module. failed_state_after_reinstall(h) or (len([ event for event in events_service.list( from_=int(last_event.id), # Fail upgrade if migration fails: # 17: Failed to switch Host to Maintenance mode # 65, 140: Migration failed # 166: No available host was found to migrate VM search='type=65 or type=140 or type=166 or type=17', ) if host.name in event.description ]) > 0), reboot=module.params['reboot_after_upgrade'], ) elif state == 'iscsidiscover': host_id = get_id_by_name(hosts_service, module.params['name']) iscsi_param = module.params['iscsi'] iscsi_targets = hosts_service.service(host_id).iscsi_discover( iscsi=otypes.IscsiDetails( port=int(iscsi_param.get('port', 3260)), username=iscsi_param.get('username'), password=iscsi_param.get('password'), address=iscsi_param.get('address'), portal=iscsi_param.get('portal'), ), ) ret = { 'changed': False, 'id': host_id, 'iscsi_targets': iscsi_targets, } elif state == 'iscsilogin': host_id = get_id_by_name(hosts_service, module.params['name']) iscsi_param = module.params['iscsi'] ret = hosts_module.action( action='iscsi_login', iscsi=otypes.IscsiDetails( port=int(iscsi_param.get('port', 3260)), username=iscsi_param.get('username'), password=iscsi_param.get('password'), address=iscsi_param.get('address'), target=iscsi_param.get('target'), portal=iscsi_param.get('portal'), ), ) elif state == 'started': ret = hosts_module.action( action='fence', action_condition=lambda h: h.status == hoststate.DOWN, wait_condition=lambda h: h.status in [hoststate.UP, hoststate.MAINTENANCE], fail_condition=hosts_module.failed_state_after_reinstall, fence_type='start', ) elif state == 'stopped': hosts_module.action( action='deactivate', action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN], wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN], fail_condition=failed_state, ) ret = hosts_module.action( action='fence', action_condition=lambda h: h.status != hoststate.DOWN, wait_condition=lambda h: h.status == hoststate.DOWN if module.params['wait'] else True, fail_condition=failed_state, fence_type='stop', ) elif state == 'restarted': ret = hosts_module.action( action='fence', wait_condition=lambda h: h.status == hoststate.UP, fail_condition=hosts_module.failed_state_after_reinstall, fence_type='restart', ) elif state == 'reinstalled': # Deactivate host if not in maintanence: hosts_module.action( action='deactivate', action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN], wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN], fail_condition=failed_state, ) # Reinstall host: hosts_module.action( action='install', action_condition=lambda h: h.status == hoststate.MAINTENANCE, post_action=hosts_module.post_reinstall, wait_condition=lambda h: h.status == hoststate.MAINTENANCE, fail_condition=hosts_module.failed_state_after_reinstall, host=otypes.Host( override_iptables=module.params['override_iptables'], ) if module.params['override_iptables'] else None, root_password=module.params['password'], ssh=otypes.Ssh(authentication_method=otypes. SshAuthenticationMethod.PUBLICKEY, ) if module.params['public_key'] else None, deploy_hosted_engine=(module.params.get('hosted_engine') == 'deploy') if module.params.get('hosted_engine') is not None else None, undeploy_hosted_engine=(module.params.get('hosted_engine') == 'undeploy') if module.params.get('hosted_engine') is not None else None, ) # Activate host after reinstall: ret = hosts_module.action( action='activate', action_condition=lambda h: h.status == hoststate.MAINTENANCE, wait_condition=lambda h: h.status == hoststate.UP, fail_condition=failed_state, ) 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_dcs_id(self): return get_id_by_name(self._get_dcs_service(), self.param('data_center'))
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': imported = False if module.params.get('external_provider') and module.params.get( 'name') not in [ net.name for net in networks_service.list() ]: # Try to import network ons_service = connection.system_service( ).openstack_network_providers_service() on_service = ons_service.provider_service( get_id_by_name(ons_service, module.params.get('external_provider'))) on_networks_service = on_service.networks_service() if module.params.get('name') in [ net.name for net in on_networks_service.list() ]: network_service = on_networks_service.network_service( get_id_by_name(on_networks_service, module.params.get('name'))) network_service.import_(data_center=otypes.DataCenter( name=module.params.get('data_center'))) imported = True ret = networks_module.create(search_params=search_params) ret['changed'] = ret['changed'] or imported # 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)