def test_ParseResultDottedDict(): url = 'https://ansible.com/blog' parts = urls.urlparse(url) dotted_parts = urls.ParseResultDottedDict(parts._asdict()) assert parts[0] == dotted_parts.scheme assert dotted_parts.as_list() == list(parts)
def wait_for_initial_license_activation(self): count = 0 uri = "/mgmt/cm/device/licensing/pool/initial-activation/{0}".format( self.want.license_key) while count < 3: response = self.client.get(uri) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) if response['contents']['status'] == 'READY': count += 1 elif response['contents'][ 'status'] == 'ACTIVATING_AUTOMATIC_NEED_EULA_ACCEPT': uri = urlparse(response['contents']['selfLink']).path self.client.patch( uri, data=dict(status='ACTIVATING_AUTOMATIC_EULA_ACCEPTED', eulaText=response['contents']['eulaText'])) elif response['contents']['status'] == 'ACTIVATION_FAILED': raise F5ModuleError(str(response['contents']['message'])) else: count = 0 time.sleep(1)
def _set_image_url(self, item): path = urlparse(item['selfLink']).path self.image_url = "https://{0}:{1}{2}".format( self.client.provider['server'], self.client.provider['server_port'], path )
def get_installed_packages_on_device(self): uri = "https://{0}:{1}/mgmt/shared/iapp/package-management-tasks".format( self.client.provider['server'], self.client.provider['server_port'] ) params = dict(operation='QUERY') resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) path = urlparse(response["selfLink"]).path task = self._wait_for_task(path) if task['status'] == 'FINISHED': return task['queryResponse'] raise F5ModuleError( "Failed to find the installed packages on the device." )
def update_on_device(self): uri = None params = None if self.want.type == "standard": params = { "command": "install", "name": self.want.image, } params.update(self.want.api_params()) uri = "/mgmt/tm/sys/software/{0}".format(self.want.image_type) self.changes.update({'message': 'Started software image installation {0} on volume {1}.'.format( self.want.image, self.want.volume)}) elif self.want.type == "vcmp": params = { "command": "install", "name": transform_name(name=self.want.block_device_image), } params.update(self.want.api_params()) uri = "/mgmt/tm/sys/software/{0}".format(transform_name(name=self.want.block_device_image_type)) self.changes.update({'message': 'Started block software image installation {0} on volume {1}.'.format( self.want.block_device_image, self.want.volume)}) response = self.client.post(uri, data=params) vol_uri = urlparse(self.volume_url).path self.changes.update({'volume_uri': '{0}'.format(vol_uri)}) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) if 'commandResult' in response['contents'] and len(response['contents']['commandResult'].strip()) > 0: raise F5ModuleError(response['contents']['commandResult']) return True
def create_on_device(self): remote_path = "/var/config/rest/downloads/{0}".format( self.want.package_file) params = dict(operation='INSTALL', packageFilePath=remote_path) response = self.client.post( '/mgmt/shared/iapp/package-management-tasks', data=params) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) path = urlparse(response['contents']['selfLink']).path task = self.wait_for_task(path) if not task: raise F5ModuleError( "Module timeout reached, state change is unknown, " "please increase the timeout parameter for long lived actions." ) if task['status'] == 'FINISHED': return True if 'errorMessage' in task: raise F5ModuleError(task['errorMessage']) else: raise F5ModuleError( "SSL Orchestrator package update failed, check BIG-IP logs for root cause." )
def create_on_device(self): remote_path = "/var/config/rest/downloads/{0}".format(self.want.package_file) params = dict( operation='INSTALL', packageFilePath=remote_path ) uri = "https://{0}:{1}/mgmt/shared/iapp/package-management-tasks".format( self.client.provider['server'], self.client.provider['server_port'] ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) path = urlparse(response["selfLink"]).path task = self._wait_for_task(path) if task['status'] == 'FINISHED': return True else: raise F5ModuleError(task['errorMessage'])
def remove_from_device(self): params = dict( operation='UNINSTALL', packageName=self.want.package_root ) uri = "https://{0}:{1}/mgmt/shared/iapp/package-management-tasks".format( self.client.provider['server'], self.client.provider['server_port'] ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) path = urlparse(response["selfLink"]).path task = self._wait_for_task(path) if task['status'] == 'FINISHED': return True return False
def _prepare_links(self, collection): purge_links = list() purge_paths = [urlparse(link).path for link in collection] for path in purge_paths: link = "https://{0}:{1}{2}".format( self.client.provider['server'], self.client.provider['server_port'], path) purge_links.append(link) return purge_links
def __del__(self): if self.last_url is None: return token = self.request.headers.get('X-F5-Auth-Token', None) if not token: return p = generic_urlparse(urlparse(self.last_url)) uri = "https://{0}:{1}/mgmt/shared/authz/tokens/{2}".format( p['hostname'], p['port'], token) self.delete(uri)
def tmos_version(client): uri = "/mgmt/tm/sys/" response = client.get(uri) if response['code'] in [200, 201]: to_parse = urlparse(response['contents']['selfLink']) query = to_parse.query version = query.split('=')[1] return version raise F5ModuleError(response['contents'])
def check_for_task(self, task): url = urlparse(task).path for x in range(0, 60): response = self.client.get( url, account_id=self.want.preferred_account_id) if response['code'] == 200: if response['contents']['status'] == 'Completed': return True if response['contents']['status'] == 'Failed': raise F5CollectionError(response['contents']['error']) else: raise F5CollectionError(response['code'], response['contents'])
def _normalize_url(self, url): ''' The hostname in URLs from vmware may be ``*`` update it accordingly ''' url_parts = generic_urlparse(urlparse(url)) if url_parts.hostname == '*': if url_parts.port: url_parts.netloc = '%s:%d' % (self.params['hostname'], url_parts.port) else: url_parts.netloc = self.params['hostname'] return urlunparse(url_parts.as_list())
def _prepare_links(self, collection): # this is to ensure no duplicates are in the provided collection no_dupes = list(set(collection)) links = list() purge_paths = [urlparse(link).path for link in no_dupes] for path in purge_paths: link = "https://{0}:{1}{2}".format( self.client.provider['server'], self.client.provider['server_port'], path) links.append(link) return links
def __del__(self): if self.last_url is None: return token = self.request.headers.get('X-F5-Auth-Token', None) if not token: return try: p = generic_urlparse(urlparse(self.last_url)) uri = "https://{0}:{1}{2}{3}".format(p['hostname'], p['port'], LOGOUT, token) self.delete(uri) except ValueError: pass
def _normalize_url(self, url): """ The hostname in URLs from vmware may be ``*`` update it accordingly """ url_parts = generic_urlparse(urlparse(url)) if url_parts.hostname == "*": if url_parts.port: url_parts.netloc = "%s:%d" % ( self.params["hostname"], url_parts.port, ) else: url_parts.netloc = self.params["hostname"] return urlunparse(url_parts.as_list())
def get_installed_packages_on_device(self): uri = "/mgmt/shared/iapp/package-management-tasks" params = {'operation': 'QUERY'} response = self.client.post(uri, data=params) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) path = urlparse(response['contents']['selfLink']).path task = self.wait_for_task(path) if task['status'] == 'FINISHED': return task['queryResponse'] raise F5ModuleError( "Failed to find the installed packages on the device.")
def remove_from_device(self): params = dict(operation='UNINSTALL', packageName=self.want.package_root) response = self.client.post( '/mgmt/shared/iapp/package-management-tasks', data=params) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) path = urlparse(response['contents']["selfLink"]).path task = self.wait_for_task(path) if task['status'] == 'FINISHED': return True return False
def create_on_device(self): remote_path = "/var/config/rest/downloads/{0}".format( self.want.package_file) params = dict(operation='INSTALL', packageFilePath=remote_path) response = self.client.post( '/mgmt/shared/iapp/package-management-tasks', data=params) if response['code'] not in [200, 201, 202]: raise F5ModuleError(response['contents']) path = urlparse(response['contents']["selfLink"]).path task = self.wait_for_task(path) if task['status'] == 'FINISHED': return True else: raise F5ModuleError(task['errorMessage'])
def tmos_version(client): uri = "https://{0}:{1}/mgmt/tm/sys/".format( client.provider['server'], client.provider['server_port'], ) resp = client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] in [400, 403]: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) to_parse = urlparse(response['selfLink']) query = to_parse.query version = query.split('=')[1] return version
def run_module(): # define available arguments/parameters a user can pass to the module module_args = dict( admin_url=dict(type='str', required=False, deafult='https://localhost:6082'), ranger_user=dict(type='str', required=True), ranger_user_password=dict(type='str', required=True), policy_type=dict(choices=['hbase', 'hdfs', 'hive', 'kafka', 'knox', 'yarn'], required=True, default=None), service_name=dict(type='str', required=True), policy_name=dict(type='str', required=True), state=dict(type='str', required=False, default='present'), description=dict(type='str', required=False), resources=dict(type='list', required=False), accesses=dict(type='str', required=False), users=dict(type='list', required=False), groups=dict(type='list', required=False), delegate_admin=dict(type='bool', required=False, default=False), is_recursive=dict(type='bool', required=False, default=False), is_enabled=dict(type='bool', required=False, default=True), is_audit_enabled=dict(type='bool', required=False, default=True), ) # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict( changed=False, original_message='', message='' ) # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) # if the user is working with this module in only check mode we do not # want to make any changes to the environment, just return the current # state with no modifications if module.check_mode: return result # manipulate or modify the state as needed (this is going to be the # part where your module will do what it needs to do) urlParts = generic_urlparse(urlparse(module.params['admin_url'])) rangerApi = RangerApi(urlParts['scheme'], urlParts['hostname'], str(urlParts['port']), "basic") rangerApi.setCredentialsBasic(module.params['ranger_user'], module.params['ranger_user_password']) if(module.params['state'] == "present"): rangerApi.postApplyPolicy(policyTemplateType = module.params['policy_type'], serviceName = module.params['service_name'], policyName = module.params['policy_name'], description = module.params['description'], resources = module.params['resources'], isRecursive = module.params['is_recursive'], users = module.params['users'], groups = module.params['groups'], accesses = module.params['accesses']) if(module.params['state'] == "absent"): rangerApi.deleteDeletePolicyByServiceAndPolicyName(module.params['service_name'], module.params['policy_name']) # use whatever logic you need to determine whether or not this module # made any modifications to your target # TODO # if module.params['new']: # result['changed'] = True # during the execution of the module, if there is an exception or a # conditional state that effectively causes a failure, run # AnsibleModule.fail_json() to pass in the message and the result # TODO # if module.params['name'] == 'fail me': # module.fail_json(msg='You requested this to fail', **result) # in the event of a successful module execution, you will want to # simple AnsibleModule.exit_json(), passing the key/value results module.exit_json(**result)
def _set_image_url(self, item): self.image_url = urlparse(item['selfLink']).path
def _set_volume_url(self, item): self.volume_url = urlparse(item['selfLink']).path