def Create(self, request, context): """ # API used https://github.com/vmware/pyvcloud/blob/master/pyvcloud/vcd/system.py#L43 """ logging.basicConfig(level=logging.DEBUG) logging.info("__INIT__Create[org_plugin]") res = org_pb2.CreateOrgResult() res.created = False try: vref = VCDClientRef() client = vref.get_ref() sys_admin = client.get_admin() system = System(client, admin_resource=sys_admin) system.create_org(request.name, request.org_full_name, request.is_enabled) logging.info("__DONE_Create[org_plugin]") res.created = True return res except Exception as e: error_message = '__ERROR_Create[org_plugin] failed {0} '.format( request.name) logging.warn(error_message, e) context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details(error_message) return res
def create_pvdc(cls): """Creates a pvdc by the name specified in the config file. Skips creating one, if such a pvdc already exists. Also stores the href and name of the provider vdc as class variables for future use. """ cls._basic_check() pvdc_name = cls._config['vcd']['default_pvdc_name'] system = System( cls._sys_admin_client, admin_resource=cls._sys_admin_client.get_admin()) pvdc_refs = system.list_provider_vdcs() if pvdc_name is not '*': for pvdc_ref in pvdc_refs: if pvdc_ref.get('name').lower() == pvdc_name.lower(): cls._logger.debug('Reusing existing ' + pvdc_name) cls._pvdc_href = pvdc_ref.get('href') cls._pvdc_name = pvdc_name return cls._logger.debug('Creating new pvdc' + pvdc_name) # TODO(VCDA-603) : use create pvdc code else: if len(pvdc_refs) > 0: cls._logger.debug('Defaulting to first pvdc in the system : ' + pvdc_refs[0].get('name')) cls._pvdc_href = pvdc_refs[0].get('href') cls._pvdc_name = pvdc_refs[0].get('name') else: cls._logger.debug('No usable pVDC found. Aborting test.') raise Exception('Test Aborted. No usable pVDC.')
def create_org(cls): """Creates an org by the name specified in the config file. Skips creating one, if such an org already exists. Also stores the href of the org as class variable for future use. """ cls._basic_check() system = System( cls._sys_admin_client, admin_resource=cls._sys_admin_client.get_admin()) org_name = cls._config['vcd']['default_org_name'] org_resource_list = cls._sys_admin_client.get_org_list() for org_resource in org_resource_list: if org_resource.get('name').lower() == org_name.lower(): cls._logger.debug('Reusing existing org ' + org_name + '.') cls._org_href = org_resource.get('href') return cls._logger.debug('Creating new org ' + org_name) system.create_org( org_name=org_name, full_org_name=org_name, is_enabled=True) # The following contraption is required to get the non admin href of # the org. The result of create_org() contains the admin version of # the href, since we created the org as a sys admin. org_resource = cls._sys_admin_client.get_org_by_name(org_name) cls._org_href = org_resource.get('href')
def create(ctx, name, full_name, enabled): try: restore_session(ctx) client = ctx.obj['client'] sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) result = system.create_org(name, full_name, enabled) stdout('Org \'%s\' is successfully created.' % result.get('name'), ctx) except Exception as e: stderr(e, ctx)
def list_netpools(ctx): try: restore_session(ctx) client = ctx.obj['client'] sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) result = [] for item in system.list_network_pools(): result.append({'name': item.get('name')}) stdout(result, ctx) except Exception as e: stderr(e, ctx)
def list_pvdc(ctx): try: restore_session(ctx) client = ctx.obj['client'] sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) result = [] for pvdc in system.list_provider_vdcs(): result.append({'name': pvdc.get('name')}) stdout(result, ctx) except Exception as e: stderr(e, ctx)
def _fill_in_netpool_default(client, vdc_kwargs): """Convert '*' value to a default netpool name""" netpool_name = vdc_kwargs['network_pool_name'] if netpool_name == '*': system = System(client, admin_resource=client.get_admin()) netpools = system.list_network_pools() for netpool in netpools: netpool_name = netpool.get('name') print("Defaulting to first netpool: {0}".format(netpool_name)) vdc_kwargs['network_pool_name'] = netpool_name break if vdc_kwargs['network_pool_name'] == '*': raise Exception("Unable to find default netpool")
def _fill_in_pvdc_default(client, vdc_kwargs): """Convert '*' value to a default pvcd name""" pvdc_name = vdc_kwargs['provider_vdc_name'] if pvdc_name == '*': system = System(client, admin_resource=client.get_admin()) pvdc_refs = system.list_provider_vdcs() for pvdc_ref in pvdc_refs: pvdc_name = pvdc_ref.get('name') print("Defaulting to first pvdc: {0}".format(pvdc_name)) vdc_kwargs['provider_vdc_name'] = pvdc_name break if vdc_kwargs['provider_vdc_name'] == '*': raise Exception("Unable to find default provider VDC")
def info_pvdc(ctx, name): try: restore_session(ctx) client = ctx.obj['client'] sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) pvdc_reference = system.get_provider_vdc(name) pvdc = PVDC(client, href=pvdc_reference.get('href')) refs = pvdc.get_vdc_references() md = pvdc.get_metadata() result = pvdc_to_dict(pvdc.get_resource(), refs, md) stdout(result, ctx) except Exception as e: stderr(e, ctx)
def test_9998_teardown(self): """Test the method System.delete_org() with force = recursive = True. Invoke the method for the organization created by setup. This test passes if no errors are generated while deleting the org. """ sys_admin_resource = TestUser._client.get_admin() system = System(TestUser._client, admin_resource=sys_admin_resource) task = system.delete_org(org_name=TestUser._new_org_name, force=True, recursive=True) result = TestUser._client.get_task_monitor().\ wait_for_success(task=task) self.assertEqual(result.get('status'), TaskStatus.SUCCESS.value)
def delete(ctx, name, recursive, force): try: restore_session(ctx) client = ctx.obj['client'] sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) if force and recursive: click.confirm( 'Do you want to force delete \'%s\' and all ' 'its objects recursively?' % name, abort=True) elif force: click.confirm( 'Do you want to force delete \'%s\'' % name, abort=True) task = system.delete_org(name, force, recursive) stdout(task, ctx) except Exception as e: stderr(e, ctx)
def Delete(self, request, context): """ # API used https://github.com/vmware/pyvcloud/blob/master/pyvcloud/vcd/system.py#L62 """ logging.info("__INIT_Delete[org_plugin]") res = org_pb2.DeleteOrgResult() res.deleted = False try: vref = VCDClientRef() client = vref.get_ref() sys_admin = client.get_admin() system = System(client, admin_resource=sys_admin) delete_org_resp = system.delete_org(request.name, request.force, request.recursive) task = client.get_task_monitor().wait_for_status( task=delete_org_resp, timeout=60, poll_frequency=2, fail_on_statuses=None, expected_target_statuses=[ TaskStatus.SUCCESS, TaskStatus.ABORTED, TaskStatus.ERROR, TaskStatus.CANCELED ], callback=None) st = task.get('status') if st == TaskStatus.SUCCESS.value: message = 'delete org status : {0} '.format(st) logging.info(message) else: raise errors.VCDOrgDeleteError( etree.tostring(task, pretty_print=True)) logging.info("__DONE_Delete[org_plugin]") res.deleted = True return res except Exception as e: error_message = '__ERROR_Delete[org_plugin] failed {0} '.format( request.name) logging.warn(error_message, e) context.set_code(grpc.StatusCode.INVALID_ARGUMENT) context.set_details(error_message) return res
def test_cleanup(self): """Get the test Org and delete it.""" client = None try: logger = Environment.get_default_logger() client = Environment.get_sys_admin_client() test_org = Environment.get_test_org(client) logger.debug('Deleting test org: {0}'.format(test_org.get_name())) sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) task = system.delete_org(test_org.get_name(), True, True) # Track the task to completion. result = client.get_task_monitor().wait_for_success(task) self.assertEqual(result.get('status'), TaskStatus.SUCCESS.value) finally: if client is not None: client.logout()
def test_0000_setup(self): """Setup a Org required for other tests in this module. Create an Org as per the configuration stated above. Tests System.create_org() method. This test passes if org href is not None. """ TestUser._client = Environment.get_sys_admin_client() sys_admin_resource = TestUser._client.get_admin() system = System(TestUser._client, admin_resource=sys_admin_resource) result = system.create_org(TestUser._new_org_name, TestUser._new_org_full_name, TestUser._new_org_enabled) TestUser._new_org_admin_href = result.get('href') TestUser._org = Org(TestUser._client, href=TestUser._new_org_admin_href) self.assertIsNotNone(TestUser._new_org_admin_href)
class VCDOrg(VcdAnsibleModule): def __init__(self, **kwargs): super(VCDOrg, self).__init__(**kwargs) def manage_states(self): state = self.params.get('state') if state == "present": return self.create() if state == "absent": return self.delete() if state == "update": return self.update() def manage_operations(self): operation = self.params.get('operation') if operation == "read": return self.read() if operation == "add_rights": return self.add_rights() if operation == "remove_rights": return self.remove_rights() if operation == "list_rights": return self.list_rights() if operation == "list_roles": return self.list_roles() if operation == "list_users": return self.list_users() if operation == "list_vdcs": return self.list_vdcs() if operation == "set_metadata": return self.set_metadata() if operation == "get_metadata": return self.get_metadata() if operation == "get_metadata_key": return self.get_metadata_key() def create(self): org_name = self.params.get('org_name') full_name = self.params.get('full_name') is_enabled = self.params.get('is_enabled') response = dict() response['changed'] = False try: sys_admin = self.client.get_admin() self.system = System(self.client, admin_resource=sys_admin) self.system.create_org(org_name, full_name, is_enabled) response['msg'] = 'Org {} has been created.'.format(org_name) response['changed'] = True except BadRequestException: response['warnings'] = 'Org {} is already present.'.format(org_name) return response def read(self): org_name = self.params.get('org_name') response = dict() org_details = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org_admin_resource = org.client.get_resource(org.href_admin) org_details['org_name'] = org_name org_details['full_name'] = str(org_admin_resource['FullName']) org_details['is_enabled'] = str(org_admin_resource['IsEnabled']) response['msg'] = org_details return response def update(self): org_name = self.params.get('org_name') is_enabled = self.params.get('is_enabled') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.update_org(is_enabled) response['msg'] = "Org {} has been updated.".format(org_name) response['changed'] = True return response def delete(self): org_name = self.params.get('org_name') force = self.params.get('force') recursive = self.params.get('recursive') response = dict() response['changed'] = False try: sys_admin = self.client.get_admin() self.system = System(self.client, admin_resource=sys_admin) delete_org_task = self.system.delete_org(org_name, force, recursive) self.execute_task(delete_org_task) response['msg'] = "Org {} has been deleted.".format(org_name) response['changed'] = True except EntityNotFoundException: response['warnings'] = "Org {} is not present.".format(org_name) return response def add_rights(self): org_name = self.params.get('org_name') org_rights = self.params.get('org_rights') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.add_rights(org_rights) response['msg'] = "Rights has been added to org successfully." response['changed'] = True return response def remove_rights(self): org_name = self.params.get('org_name') org_rights = self.params.get('org_rights') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.remove_rights(org_rights) response['msg'] = "Rights has been removed to org successfully." response['changed'] = True return response def list_rights(self): org_name = self.params.get('org_name') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) response['msg'] = org.list_rights_of_org() return response def list_roles(self): org_name = self.params.get('org_name') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) response['msg'] = org.list_roles() return response def list_users(self): org_name = self.params.get('org_name') response = dict() org_details = dict() response['users'] = list() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org_user_list = org.list_users() resource_type = ResourceType.USER.value if self.client.is_sysadmin(): resource_type = ResourceType.ADMIN_USER.value for org_user in org_user_list: response['users'].append( to_dict(org_user, resource_type=resource_type, exclude=[])) return response def list_vdcs(self): org_name = self.params.get('org_name') response = dict() org_details = dict() response['vdcs'] = list() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) response['vdcs'] = org.list_vdcs() return response def get_metadata(self): org_name = self.params.get('org_name') metadata = self.params.get('metadata') response = dict() response['msg'] = '' all_metadata = dict() # self.metadata_visibility = # self.metadata_domain = if len(metadata) != 0: # workaround to set metadata for org as it is as of now not implemented in pyvcloud for org, vdc, e.g. - we will open a pull request to fix this in the future resource = self.client.get_linked_resource(self.client.get_org_by_name(org_name), RelationType.DOWN, EntityType.METADATA.value) self.metadata = Metadata(self.client, resource=resource) for md in metadata: domain = MetadataDomain.SYSTEM visibility = MetadataVisibility.READONLY if type(md) is dict and md.get('state', 'present') == 'absent': if md.get('visibility', 'READONLY').upper() == 'READWRITE': domain = MetadataDomain.GENERAL self.metadata.remove_metadata(md['name'], domain) else: if md.get('visibility', 'READONLY').upper() == 'PRIVATE': visibility = MetadataVisibility.PRIVATE elif md.get('visibility', 'READONLY').upper() == 'READWRITE': domain = MetadataDomain.GENERAL visibility = MetadataVisibility.READWRITE value_type = MetadataValueType.STRING if md.get('type', 'STRING').upper() == 'NUMBER': value_type = MetadataValueType.NUMBER elif md.get('type', 'STRING').upper() == 'BOOLEAN': value_type = MetadataValueType.BOOLEAN elif md.get('type', 'STRING').upper() == 'DATA_TIME': value_type = MetadataValueType.DATA_TIME self.metadata.get_metadata(md['name'], md['value'], domain, visibility, value_type, True) all_metadata[md['name']].append(md)) return response def set_metadata(self): org_name = self.params.get('org_name') metadata = self.params.get('metadata') response = dict() response['msg'] = '' if len(metadata) != 0: # workaround to set metadata for org as it is as of now not implemented in pyvcloud for org, vdc, e.g. - we will open a pull request to fix this in the future resource = self.client.get_linked_resource(self.client.get_org_by_name(org_name), RelationType.DOWN, EntityType.METADATA.value) self.metadata = Metadata(self.client, resource=resource) for md in metadata: domain = MetadataDomain.SYSTEM visibility = MetadataVisibility.READONLY if type(md) is dict and md.get('state', 'present') == 'absent': if md.get('visibility', 'READONLY').upper() == 'READWRITE': domain = MetadataDomain.GENERAL self.metadata.remove_metadata(md['name'], domain) else: if md.get('visibility', 'READONLY').upper() == 'PRIVATE': visibility = MetadataVisibility.PRIVATE elif md.get('visibility', 'READONLY').upper() == 'READWRITE': domain = MetadataDomain.GENERAL visibility = MetadataVisibility.READWRITE value_type = MetadataValueType.STRING if md.get('type', 'STRING').upper() == 'NUMBER': value_type = MetadataValueType.NUMBER elif md.get('type', 'STRING').upper() == 'BOOLEAN': value_type = MetadataValueType.BOOLEAN elif md.get('type', 'STRING').upper() == 'DATA_TIME': value_type = MetadataValueType.DATA_TIME self.metadata.set_metadata(md['name'], md['value'], domain, visibility, value_type, True) return response
def __init__(self, **kwargs): super(VCDOrg, self).__init__(**kwargs) sys_admin = self.client.get_admin() self.system = System(self.client, admin_resource=sys_admin)
def test_create_org(self): sys_admin = self.client.get_admin() system = System(self.client, admin_resource=sys_admin) org = system.create_org(self.config['vcd']['org_name'], self.config['vcd']['org_full_name']) assert org.get('name') == self.config['vcd']['org_name']
def create_org(client): logging.info("create org %s", str(client)) sys_admin = client.get_admin() system = System(client, admin_resource=sys_admin) task = system.create_org("O2", "O2 ORG") print(type(task))
def create_org_vdc(self, vdc_name, provider_vdc_name, description='', allocation_model='AllocationVApp', cpu_units='MHz', cpu_allocated=0, cpu_limit=0, mem_units='MB', mem_allocated=0, mem_limit=0, nic_quota=0, network_quota=0, vm_quota=0, storage_profiles=[], resource_guaranteed_memory=None, resource_guaranteed_cpu=None, vcpu_in_mhz=None, is_thin_provision=None, network_pool_name=None, uses_fast_provisioning=None, over_commit_allowed=None, vm_discovery_enabled=None, is_enabled=True): """Create Organization VDC in the current Org. :param vdc_name (str): The name of the new org vdc. :param provider_vdc_name (str): The name of an existing provider vdc. :param description (str): The description of the new org vdc. :param allocation_model (str): The allocation model used by this vDC. One of AllocationVApp, AllocationPool or ReservationPool. :param cpu_units (str): The cpu units compute capacity allocated to this vDC. One of MHz or GHz :param cpu_allocated (int): Capacity that is committed to be available. :param cpu_limit (int): Capacity limit relative to the value specified for Allocation. :param mem_units (str): The memory units compute capacity allocated to this vDC. One of MB or GB. :param mem_allocated (int): Memory capacity that is committed to be available. :param mem_limit (int): Memory capacity limit relative to the value specified for Allocation. :param nic_quota (int): Maximum number of virtual NICs allowed in this vDC. Defaults to 0, which specifies an unlimited number. :param network_quota (int): Maximum number of network objects that can be deployed in this vDC. Defaults to 0, which means no networks can be deployed. :param vm_quota (int): The maximum number of VMs that can be created in this vDC. Defaults to 0, which specifies an unlimited number. :param storage_profiles: List of provider vDC storage profiles to add to this vDC. Each item is a dictionary that should include the following elements: name: (string) name of the PVDC storage profile. enabled: (bool) True if the storage profile is enabled for this vDC. units: (string) Units used to define limit. One of MB or GB. limit: (int) Max number of units allocated for this storage profile. default: (bool) True if this is default storage profile for this vDC. :param resource_guaranteed_memory (float): Percentage of allocated CPU resources guaranteed to vApps deployed in this vDC. Value defaults to 1.0 if the element is empty. :param resource_guaranteed_cpu (float): Percentage of allocated memory resources guaranteed to vApps deployed in this vDC. Value defaults to 1.0 if the element is empty. :param vcpu_in_mhz (int): Specifies the clock frequency, in Megahertz, for any virtual CPU that is allocated to a VM. :param is_thin_provision (bool): Boolean to request thin provisioning. :param network_pool_name (str): Reference to a network pool in the Provider vDC. :param uses_fast_provisioning (bool): Boolean to request fast provisioning. :param over_commit_allowed (bool): Set to false to disallow creation of the VDC if the AllocationModel is AllocationPool or ReservationPool and the ComputeCapacity you specified is greater than what the backing Provider VDC can supply. Defaults to true if empty or missing. :param vm_discovery_enabled (bool): True if discovery of vCenter VMs is enabled for resource pools backing this vDC. :param is_enabled (bool): True if this vDC is enabled for use by the organization users. :return: A :class:`lxml.objectify.StringElement` object describing the new VDC. """ if self.resource is None: self.resource = self.client.get_resource(self.href) sys_admin_resource = self.client.get_admin() system = System(self.client, admin_resource=sys_admin_resource) pvdc = system.get_provider_vdc(provider_vdc_name) resource_admin = self.client.get_resource(self.href_admin) params = E.CreateVdcParams( E.Description(description), E.AllocationModel(allocation_model), E.ComputeCapacity( E.Cpu( E.Units(cpu_units), E.Allocated(cpu_allocated), E.Limit(cpu_limit)), E.Memory( E.Units(mem_units), E.Allocated(mem_allocated), E.Limit(mem_limit))), E.NicQuota(nic_quota), E.NetworkQuota(network_quota), E.VmQuota(vm_quota), E.IsEnabled(is_enabled), name=vdc_name) for sp in storage_profiles: pvdc_sp = system.get_provider_vdc_storage_profile(sp['name']) params.append( E.VdcStorageProfile( E.Enabled(sp['enabled']), E.Units(sp['units']), E.Limit(sp['limit']), E.Default(sp['default']), E.ProviderVdcStorageProfile(href=pvdc_sp.get('href')))) if resource_guaranteed_memory is not None: params.append( E.ResourceGuaranteedMemory(resource_guaranteed_memory)) if resource_guaranteed_cpu is not None: params.append(E.ResourceGuaranteedCpu(resource_guaranteed_cpu)) if vcpu_in_mhz is not None: params.append(E.VCpuInMhz(vcpu_in_mhz)) if is_thin_provision is not None: params.append(E.IsThinProvision(is_thin_provision)) if network_pool_name is not None: npr = system.get_network_pool_reference(network_pool_name) href = npr.get('href') params.append( E.NetworkPoolReference( href=href, id=href.split('/')[-1], type=npr.get('type'), name=npr.get('name'))) params.append(pvdc) if uses_fast_provisioning is not None: params.append(E.UsesFastProvisioning(uses_fast_provisioning)) if over_commit_allowed is not None: params.append(E.OverCommitAllowed(over_commit_allowed)) if vm_discovery_enabled is not None: params.append(E.VmDiscoveryEnabled(vm_discovery_enabled)) return self.client.post_linked_resource( resource_admin, RelationType.ADD, EntityType.VDCS_PARAMS.value, params)
def create_ovdc(cls): """Creates an org vdc with the name specified in the config file. Skips creating one, if such an org vdc already exists. Also stores the href of the org vdc as class variable for future use. :raises: Exception: if the class variable _org_href or _pvdc_name is not populated. """ cls._basic_check() if cls._org_href is None: raise Exception('Org ' + cls._config['vcd']['default_org_name'] + ' doesn\'t exist.') if cls._pvdc_name is None: raise Exception('pVDC ' + cls._config['vcd']['default_pvdc_name'] + ' doesn\'t exist.') if cls._org_admin_client is None: cls._org_admin_client = cls.get_client_in_default_org( CommonRoles.ORGANIZATION_ADMINISTRATOR) org = Org(cls._org_admin_client, href=cls._org_href) ovdc_name = cls._config['vcd']['default_ovdc_name'] for vdc in org.list_vdcs(): if vdc.get('name').lower() == ovdc_name.lower(): cls._logger.debug('Reusing existing ovdc ' + ovdc_name + '.') cls._ovdc_href = vdc.get('href') return org = Org(cls._sys_admin_client, href=cls._org_href) storage_profiles = [{ 'name': cls._config['vcd']['default_storage_profile_name'], 'enabled': True, 'units': 'MB', 'limit': 0, 'default': True }] system = System(cls._sys_admin_client, admin_resource=cls._sys_admin_client.get_admin()) netpool_to_use = cls._get_netpool_name_to_use(system) cls._logger.debug('Creating ovdc ' + ovdc_name + '.') vdc_resource = org.create_org_vdc( ovdc_name, cls._pvdc_name, network_pool_name=netpool_to_use, network_quota=cls._config['vcd']['default_network_quota'], storage_profiles=storage_profiles, uses_fast_provisioning=True, is_thin_provision=True) cls._sys_admin_client.get_task_monitor().wait_for_success( task=vdc_resource.Tasks.Task[0]) org = Org(cls._org_admin_client, href=cls._org_href) # The following contraption is required to get the non admin href of # the ovdc. vdc_resource contains the admin version of the href since # we created the ovdc as a sys admin. for vdc in org.list_vdcs(): if vdc.get('name').lower() == ovdc_name.lower(): cls._ovdc_href = vdc.get('href')
def get_system_object(self): client = self.module.client sys_admin = client.get_admin() system = System(client, admin_resource=sys_admin) return system
def create_org(client): logging.info("create org %s", str(client)) sys_admin = client.get_admin() system = System(client, admin_resource=sys_admin) system.create_org("O2", "O2 ORG")
client.set_highest_supported_version() client.set_credentials( BasicLoginCredentials(cfg.vcd_admin_user, "System", cfg.vcd_admin_password)) # Ensure the org exists. print("Fetching org...") try: # This call gets a record that we can turn into an Org class. org_record = client.get_org_by_name(cfg.org) org = Org(client, href=org_record.get('href')) print("Org already exists: {0}".format(org.get_name())) except Exception: print("Org does not exist, creating: {0}".format(cfg.org)) sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) admin_org_resource = system.create_org(cfg.org, "Test Org", True) org_record = client.get_org_by_name(cfg.org) org = Org(client, href=org_record.get('href')) print("Org now exists: {0}".format(org.get_name())) # Ensure user exists on the org. try: user_resource = org.get_user(cfg.user['name']) print("User already exists: {0}".format(cfg.user['name'])) except Exception: print("User does not exist, creating: {0}".format(cfg.user['name'])) role_record = org.get_role_record(cfg.user['role']) user_resource = org.create_user(user_name=cfg.user['name'], password=cfg.user['password'], role_href=role_record.get('href'))
print("Logging in...") client = Client(cfg.vcd_host, verify_ssl_certs=False, log_file='pyvcloud.log', log_requests=True, log_headers=True, log_bodies=True) client.set_credentials( BasicLoginCredentials(cfg.vcd_admin_user, "System", cfg.vcd_admin_password)) # Load the org. If it does not exist, there's nothing to do. print("Fetching Org...") try: org_record = client.get_org_by_name(cfg.org) except Exception: print("Org does not exist, nothing to be done") sys.exit(0) # Delete the org. print("Org exists, deleting: {0}".format(cfg.org)) sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) resource = system.delete_org(cfg.org, True, True) handle_task(client, resource) print("Deleted the org...") # Log out. print("All done!") client.logout()
log_bodies=True) client.set_highest_supported_version() client.set_credentials(BasicLoginCredentials(cfg.vcd_admin_user, "System", cfg.vcd_admin_password)) # Ensure the org exists. print("Fetching org...") try: # This call gets a record that we can turn into an Org class. org_record = client.get_org_by_name(cfg.org) org = Org(client, href=org_record.get('href')) print("Org already exists: {0}".format(org.get_name())) except Exception: print("Org does not exist, creating: {0}".format(cfg.org)) sys_admin_resource = client.get_admin() system = System(client, admin_resource=sys_admin_resource) admin_org_resource = system.create_org(cfg.org, "Test Org", True) org_record = client.get_org_by_name(cfg.org) org = Org(client, href=org_record.get('href')) print("Org now exists: {0}".format(org.get_name())) # Ensure user exists on the org. try: user_resource = org.get_user(cfg.user['name']) print("User already exists: {0}".format(cfg.user['name'])) except Exception: print("User does not exist, creating: {0}".format(cfg.user['name'])) role_record = org.get_role_record(cfg.user['role']) user_resource = org.create_user(user_name=cfg.user['name'], password=cfg.user['password'], role_href=role_record.get('href'))
def test_delete_org(self): system = System(self.client) system.delete_org(self.config['vcd']['org_name'], True, True)
def create_org_vdc(self, vdc_name, provider_vdc_name, description='', allocation_model='AllocationVApp', cpu_units='MHz', cpu_allocated=0, cpu_limit=0, mem_units='MB', mem_allocated=0, mem_limit=0, nic_quota=0, network_quota=0, vm_quota=0, storage_profiles=[], resource_guaranteed_memory=None, resource_guaranteed_cpu=None, vcpu_in_mhz=None, is_thin_provision=None, network_pool_name=None, uses_fast_provisioning=None, over_commit_allowed=None, vm_discovery_enabled=None, is_enabled=True): """Create Organization VDC in the current Org. :param vdc_name (str): The name of the new org vdc. :param provider_vdc_name (str): The name of an existing provider vdc. :param description (str): The description of the new org vdc. :param allocation_model (str): The allocation model used by this vDC. One of AllocationVApp, AllocationPool or ReservationPool. :param cpu_units (str): The cpu units compute capacity allocated to this vDC. One of MHz or GHz :param cpu_allocated (int): Capacity that is committed to be available. :param cpu_limit (int): Capacity limit relative to the value specified for Allocation. :param mem_units (str): The memory units compute capacity allocated to this vDC. One of MB or GB. :param mem_allocated (int): Memory capacity that is committed to be available. :param mem_limit (int): Memory capacity limit relative to the value specified for Allocation. :param nic_quota (int): Maximum number of virtual NICs allowed in this vDC. Defaults to 0, which specifies an unlimited number. :param network_quota (int): Maximum number of network objects that can be deployed in this vDC. Defaults to 0, which means no networks can be deployed. :param vm_quota (int): The maximum number of VMs that can be created in this vDC. Defaults to 0, which specifies an unlimited number. :param storage_profiles: List of provider vDC storage profiles to add to this vDC. Each item is a dictionary that should include the following elements: name: (string) name of the PVDC storage profile. enabled: (bool) True if the storage profile is enabled for this vDC. units: (string) Units used to define limit. One of MB or GB. limit: (int) Max number of units allocated for this storage profile. default: (bool) True if this is default storage profile for this vDC. :param resource_guaranteed_memory (float): Percentage of allocated CPU resources guaranteed to vApps deployed in this vDC. Value defaults to 1.0 if the element is empty. :param resource_guaranteed_cpu (float): Percentage of allocated memory resources guaranteed to vApps deployed in this vDC. Value defaults to 1.0 if the element is empty. :param vcpu_in_mhz (int): Specifies the clock frequency, in Megahertz, for any virtual CPU that is allocated to a VM. :param is_thin_provision (bool): Boolean to request thin provisioning. :param network_pool_name (str): Reference to a network pool in the Provider vDC. :param uses_fast_provisioning (bool): Boolean to request fast provisioning. :param over_commit_allowed (bool): Set to false to disallow creation of the VDC if the AllocationModel is AllocationPool or ReservationPool and the ComputeCapacity you specified is greater than what the backing Provider VDC can supply. Defaults to true if empty or missing. :param vm_discovery_enabled (bool): True if discovery of vCenter VMs is enabled for resource pools backing this vDC. :param is_enabled (bool): True if this vDC is enabled for use by the organization users. :return: A :class:`lxml.objectify.StringElement` object describing the new VDC. """ if self.resource is None: self.resource = self.client.get_resource(self.href) sys_admin_resource = self.client.get_admin() system = System(self.client, admin_resource=sys_admin_resource) pvdc = system.get_provider_vdc(provider_vdc_name) resource_admin = self.client.get_resource(self.href_admin) params = E.CreateVdcParams(E.Description(description), E.AllocationModel(allocation_model), E.ComputeCapacity( E.Cpu(E.Units(cpu_units), E.Allocated(cpu_allocated), E.Limit(cpu_limit)), E.Memory(E.Units(mem_units), E.Allocated(mem_allocated), E.Limit(mem_limit))), E.NicQuota(nic_quota), E.NetworkQuota(network_quota), E.VmQuota(vm_quota), E.IsEnabled(is_enabled), name=vdc_name) for sp in storage_profiles: pvdc_sp = system.get_provider_vdc_storage_profile(sp['name']) params.append( E.VdcStorageProfile( E.Enabled(sp['enabled']), E.Units(sp['units']), E.Limit(sp['limit']), E.Default(sp['default']), E.ProviderVdcStorageProfile(href=pvdc_sp.get('href')))) if resource_guaranteed_memory is not None: params.append( E.ResourceGuaranteedMemory(resource_guaranteed_memory)) if resource_guaranteed_cpu is not None: params.append(E.ResourceGuaranteedCpu(resource_guaranteed_cpu)) if vcpu_in_mhz is not None: params.append(E.VCpuInMhz(vcpu_in_mhz)) if is_thin_provision is not None: params.append(E.IsThinProvision(is_thin_provision)) if network_pool_name is not None: npr = system.get_network_pool_reference(network_pool_name) href = npr.get('href') params.append( E.NetworkPoolReference(href=href, id=href.split('/')[-1], type=npr.get('type'), name=npr.get('name'))) params.append(pvdc) if uses_fast_provisioning is not None: params.append(E.UsesFastProvisioning(uses_fast_provisioning)) if over_commit_allowed is not None: params.append(E.OverCommitAllowed(over_commit_allowed)) if vm_discovery_enabled is not None: params.append(E.VmDiscoveryEnabled(vm_discovery_enabled)) return self.client.post_linked_resource(resource_admin, RelationType.ADD, EntityType.VDCS_PARAMS.value, params)
class VCDOrg(VcdAnsibleModule): def __init__(self, **kwargs): super(VCDOrg, self).__init__(**kwargs) def manage_states(self): state = self.params.get('state') if state == "present": return self.create() if state == "absent": return self.delete() if state == "update": return self.update() def manage_operations(self): operation = self.params.get('operation') if operation == "read": return self.read() if operation == "add_rights": return self.add_rights() if operation == "remove_rights": return self.remove_rights() if operation == "list_rights": return self.list_rights() if operation == "list_roles": return self.list_roles() def create(self): org_name = self.params.get('org_name') full_name = self.params.get('full_name') is_enabled = self.params.get('is_enabled') response = dict() response['changed'] = False try: sys_admin = self.client.get_admin() self.system = System(self.client, admin_resource=sys_admin) self.system.create_org(org_name, full_name, is_enabled) response['msg'] = 'Org {} has been created.'.format(org_name) response['changed'] = True except BadRequestException: response['warnings'] = 'Org {} is already present.'.format( org_name) return response def read(self): org_name = self.params.get('org_name') response = dict() org_details = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org_admin_resource = org.client.get_resource(org.href_admin) org_details['org_name'] = org_name org_details['full_name'] = str(org_admin_resource['FullName']) org_details['is_enabled'] = str(org_admin_resource['IsEnabled']) response['msg'] = org_details return response def update(self): org_name = self.params.get('org_name') is_enabled = self.params.get('is_enabled') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.update_org(is_enabled) response['msg'] = "Org {} has been updated.".format(org_name) response['changed'] = True return response def delete(self): org_name = self.params.get('org_name') force = self.params.get('force') recursive = self.params.get('recursive') response = dict() response['changed'] = False try: sys_admin = self.client.get_admin() self.system = System(self.client, admin_resource=sys_admin) delete_org_task = self.system.delete_org(org_name, force, recursive) self.execute_task(delete_org_task) response['msg'] = "Org {} has been deleted.".format(org_name) response['changed'] = True except EntityNotFoundException: response['warnings'] = "Org {} is not present.".format(org_name) return response def add_rights(self): org_name = self.params.get('org_name') org_rights = self.params.get('org_rights') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.add_rights(org_rights) response['msg'] = "Rights has been added to org successfully." response['changed'] = True return response def remove_rights(self): org_name = self.params.get('org_name') org_rights = self.params.get('org_rights') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) org.remove_rights(org_rights) response['msg'] = "Rights has been removed to org successfully." response['changed'] = True return response def list_rights(self): org_name = self.params.get('org_name') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) response['msg'] = org.list_rights_of_org() return response def list_roles(self): org_name = self.params.get('org_name') response = dict() response['changed'] = False resource = self.client.get_org_by_name(org_name) org = Org(self.client, resource=resource) response['msg'] = org.list_roles() return response
def test_05_create_org_ldap_settings_custom(self): ''' Create organization with LDAP settings CUSTOM ''' sys_admin = self.client.get_admin() system = System(self.client, admin_resource=sys_admin) # Test data (org_name, org_desc) = self.get_org_data() ldap_mode = 'CUSTOM' custom_hostname = 'localhost' custom_port = 8080 custom_is_ssl = True custom_is_ssl_accept_all = True custom_username = '******' custom_password = '******' custom_auth_mechanism = 'SIMPLE' custom_connector_type = 'OPEN_LDAP' custom_is_group_search_base_enabled = False custom_user_object_class = 'user' custom_user_object_identifier = 'objectGuid' custom_user_username = '******' custom_user_email = '*****@*****.**' custom_user_full_name = 'First Last' custom_user_given_name = 'First' custom_user_surname = 'Last' custom_user_telephone = '+61430088000' custom_user_group_membership_identifier = 'dn' custom_user_group_back_link_identifier = 'abc' custom_group_object_class = 'group' custom_group_object_identifier = 'dn' custom_group_group_name = 'cn' custom_group_membership = 'member' custom_group_membership_identifier = 'dn' custom_group_back_link_identifier = 'abc' custom_use_external_kerberos = False settings = OrgSettings() settings.set_org_ldap_settings(org_ldap_mode=ldap_mode, cus_hostname=custom_hostname, cus_port=custom_port, cus_is_ssl=custom_is_ssl, cus_is_ssl_accept_all=custom_is_ssl_accept_all, cus_username=custom_username, cus_password=custom_password, cus_auth_mechanism=custom_auth_mechanism, cus_connector_type=custom_connector_type, cus_is_grp_search_base_enabled=custom_is_group_search_base_enabled, cus_user_object_class=custom_user_object_class, cus_user_object_id=custom_user_object_identifier, cus_user_username=custom_user_username, cus_user_email=custom_user_email, cus_user_full_name=custom_user_full_name, cus_user_given_name=custom_user_given_name, cus_user_surname=custom_user_surname, cus_user_telephone=custom_user_telephone, cus_user_grp_membership_id=custom_user_group_membership_identifier, cus_user_grp_back_link_id=custom_user_group_back_link_identifier, cus_grp_object_class=custom_group_object_class, cus_grp_object_id=custom_group_object_identifier, cus_grp_grp_name=custom_group_group_name, cus_grp_membership=custom_group_membership, cus_grp_membership_id=custom_group_membership_identifier, cus_grp_back_link_id=custom_group_back_link_identifier, cus_use_external_kerberos=custom_use_external_kerberos) org = system.create_org(org_name, org_desc, settings=settings) ldap = org.Settings.OrgLdapSettings # Verifications assert org.get('name') == org_name assert ldap.OrgLdapMode.text == ldap_mode assert ldap.CustomOrgLdapSettings.HostName.text == custom_hostname assert int(ldap.CustomOrgLdapSettings.Port.text) == custom_port assert ldap.CustomOrgLdapSettings.IsSsl.text == str(custom_is_ssl).lower() assert ldap.CustomOrgLdapSettings.IsSslAcceptAll.text == str(custom_is_ssl_accept_all).lower() assert ldap.CustomOrgLdapSettings.UserName.text == custom_username # Password is not returned so no assert for password assert ldap.CustomOrgLdapSettings.AuthenticationMechanism.text == custom_auth_mechanism assert ldap.CustomOrgLdapSettings.IsGroupSearchBaseEnabled.text == str(custom_is_group_search_base_enabled).lower() assert ldap.CustomOrgLdapSettings.ConnectorType.text == custom_connector_type assert ldap.CustomOrgLdapSettings.UserAttributes.ObjectClass.text == custom_user_object_class assert ldap.CustomOrgLdapSettings.UserAttributes.ObjectIdentifier.text == custom_user_object_identifier assert ldap.CustomOrgLdapSettings.UserAttributes.UserName.text == custom_user_username assert ldap.CustomOrgLdapSettings.UserAttributes.Email.text == custom_user_email assert ldap.CustomOrgLdapSettings.UserAttributes.FullName.text == custom_user_full_name assert ldap.CustomOrgLdapSettings.UserAttributes.GivenName.text == custom_user_given_name assert ldap.CustomOrgLdapSettings.UserAttributes.Surname.text == custom_user_surname assert ldap.CustomOrgLdapSettings.UserAttributes.Telephone.text == custom_user_telephone assert ldap.CustomOrgLdapSettings.UserAttributes.GroupMembershipIdentifier.text == custom_user_group_membership_identifier assert ldap.CustomOrgLdapSettings.UserAttributes.GroupBackLinkIdentifier.text == custom_user_group_back_link_identifier assert ldap.CustomOrgLdapSettings.GroupAttributes.ObjectClass.text == custom_group_object_class assert ldap.CustomOrgLdapSettings.GroupAttributes.ObjectIdentifier.text == custom_group_object_identifier assert ldap.CustomOrgLdapSettings.GroupAttributes.GroupName.text == custom_group_group_name assert ldap.CustomOrgLdapSettings.GroupAttributes.Membership.text == custom_group_membership assert ldap.CustomOrgLdapSettings.GroupAttributes.MembershipIdentifier.text == custom_group_membership_identifier assert ldap.CustomOrgLdapSettings.GroupAttributes.BackLinkIdentifier.text == custom_group_back_link_identifier assert ldap.CustomOrgLdapSettings.UseExternalKerberos.text == str(custom_use_external_kerberos).lower() # Cleanup delete the organization system.delete_org(org_name, True, True)