def grafana_list_dashboards(self): # define http headers headers = self.grafana_headers() dashboard_list = [] try: if self.search: r = open_url('%s/api/search?query=%s' % (self.grafana_url, self.search), headers=headers, method='GET') else: r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET') except HTTPError as e: raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e)) if r.getcode() == 200: try: dashboard_list = json.loads(r.read()) except Exception as e: raise GrafanaAPIException('Unable to parse json list %s' % to_native(e)) else: raise GrafanaAPIException( 'Unable to list grafana dashboards : %s' % str(r.getcode())) return dashboard_list
def test_open_url(urlopen_mock, install_opener_mock, mocker): req_mock = mocker.patch( 'ansible_collections.notstdlib.moveitallout.plugins.module_utils.urls.Request.open' ) open_url('https://ansible.com/') req_mock.assert_called_once_with('GET', 'https://ansible.com/', data=None, headers=None, use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=False, follow_redirects='urllib2', client_cert=None, client_key=None, cookies=None, use_gssapi=False, unix_socket=None, ca_path=None, unredirected_headers=None)
def request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False): try: r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) except HTTPError as err: r = err.fp try: raw_data = r.read() if raw_data: data = json.loads(raw_data) else: raw_data = None except Exception: if ignore_errors: pass else: raise Exception(raw_data) resp_code = r.getcode() if resp_code >= 400 and not ignore_errors: raise Exception(resp_code, data) else: return resp_code, data
def get_token(base_url, validate_certs, auth_realm, client_id, auth_username, auth_password, client_secret): auth_url = URL_TOKEN.format(url=base_url, realm=auth_realm) temp_payload = { 'grant_type': 'password', 'client_id': client_id, 'client_secret': client_secret, 'username': auth_username, 'password': auth_password, } # Remove empty items, for instance missing client_secret payload = dict((k, v) for k, v in temp_payload.items() if v is not None) try: r = json.load( open_url(auth_url, method='POST', validate_certs=validate_certs, data=urlencode(payload))) except ValueError as e: raise KeycloakError( 'API returned invalid JSON when trying to obtain access token from %s: %s' % (auth_url, str(e))) except Exception as e: raise KeycloakError('Could not obtain access token from %s: %s' % (auth_url, str(e))) try: return { 'Authorization': 'Bearer ' + r['access_token'], 'Content-Type': 'application/json' } except KeyError: raise KeycloakError('Could not obtain access token from %s' % auth_url)
def get_group_by_groupid(self, gid, realm="master"): """ Fetch a keycloak group from the provided realm using the group's unique ID. If the group does not exist, None is returned. gid is a UUID provided by the Keycloak API :param gid: UUID of the group to be returned :param realm: Realm in which the group resides; default 'master'. """ groups_url = URL_GROUP.format(url=self.baseurl, realm=realm, groupid=gid) try: return json.load( open_url(groups_url, method="GET", headers=self.restheaders, validate_certs=self.validate_certs)) except HTTPError as e: if e.code == 404: return None else: self.module.fail_json( msg="Could not fetch group %s in realm %s: %s" % (gid, realm, str(e))) except Exception as e: self.module.fail_json( msg="Could not fetch group %s in realm %s: %s" % (gid, realm, str(e)))
def get_client_by_id(self, id, realm='master'): """ Obtain client representation by id :param id: id (not clientId) of client to be queried :param realm: client from this realm :return: dict of client representation or None if none matching exist """ client_url = URL_CLIENT.format(url=self.baseurl, realm=realm, id=id) try: return json.load( open_url(client_url, method='GET', headers=self.restheaders, validate_certs=self.validate_certs)) except HTTPError as e: if e.code == 404: return None else: self.module.fail_json( msg='Could not obtain client %s for realm %s: %s' % (id, realm, str(e))) except ValueError as e: self.module.fail_json( msg= 'API returned incorrect JSON when trying to obtain client %s for realm %s: %s' % (id, realm, str(e))) except Exception as e: self.module.fail_json( msg='Could not obtain client %s for realm %s: %s' % (id, realm, str(e)))
def get_clients(self, realm='master', filter=None): """ Obtains client representations for clients in a realm :param realm: realm to be queried :param filter: if defined, only the client with clientId specified in the filter is returned :return: list of dicts of client representations """ clientlist_url = URL_CLIENTS.format(url=self.baseurl, realm=realm) if filter is not None: clientlist_url += '?clientId=%s' % filter try: return json.load( open_url(clientlist_url, method='GET', headers=self.restheaders, validate_certs=self.validate_certs)) except ValueError as e: self.module.fail_json( msg= 'API returned incorrect JSON when trying to obtain list of clients for realm %s: %s' % (realm, str(e))) except Exception as e: self.module.fail_json( msg='Could not obtain list of clients for realm %s: %s' % (realm, str(e)))
def run(self, terms, variables, **kwargs): try: resp = open_url('https://ip-ranges.amazonaws.com/ip-ranges.json') amazon_response = json.load(resp)['prefixes'] except getattr(json.decoder, 'JSONDecodeError', ValueError) as e: # on Python 3+, json.decoder.JSONDecodeError is raised for bad # JSON. On 2.x it's a ValueError raise AnsibleError("Could not decode AWS IP ranges: %s" % to_native(e)) except HTTPError as e: raise AnsibleError( "Received HTTP error while pulling IP ranges: %s" % to_native(e)) except SSLValidationError as e: raise AnsibleError( "Error validating the server's certificate for: %s" % to_native(e)) except URLError as e: raise AnsibleError("Failed look up IP range service: %s" % to_native(e)) except ConnectionError as e: raise AnsibleError("Error connecting to IP range service: %s" % to_native(e)) if 'region' in kwargs: region = kwargs['region'] amazon_response = (item for item in amazon_response if item['region'] == region) if 'service' in kwargs: service = str.upper(kwargs['service']) amazon_response = (item for item in amazon_response if item['service'] == service) return [item['ip_prefix'] for item in amazon_response]
def get(self, key): url = "%s/%s?recursive=true" % (self.baseurl, key) data = None value = {} try: r = open_url(url, validate_certs=self.validate_certs) data = r.read() except Exception: return None try: # I will not support Version 1 of etcd for folder parsing item = json.loads(data) if self.version == 'v1': # When ETCD are working with just v1 if 'value' in item: value = item['value'] else: if 'node' in item: # When a usual result from ETCD value = self._parse_node(item['node']) if 'errorCode' in item: # Here return an error when an unknown entry responds value = "ENOENT" except Exception: raise return value
def send_msg_v2(self, msg, msg_format='text', color='yellow', notify=False): """Method for sending a message to HipChat""" headers = { 'Authorization': 'Bearer %s' % self.token, 'Content-Type': 'application/json' } body = {} body['room_id'] = self.room body['from'] = self.from_name[:15] # max length is 15 body['message'] = msg body['message_format'] = msg_format body['color'] = color body['notify'] = self.allow_notify and notify data = json.dumps(body) url = self.API_V2_URL + "room/{room_id}/notification".format( room_id=self.room) try: response = open_url(url, data=data, headers=headers, method='POST') return response.read() except Exception as ex: self._display.warning( 'Could not submit message to hipchat: {0}'.format(ex))
def _fetch_information(token, url): results = [] paginated_url = url while True: try: response = open_url(paginated_url, headers={ 'X-Auth-Token': token, 'Content-type': 'application/json' }) except Exception as e: raise AnsibleError("Error while fetching %s: %s" % (url, to_native(e))) try: raw_json = json.loads(response.read()) except ValueError: raise AnsibleError("Incorrect JSON payload") try: results.extend(raw_json["servers"]) except KeyError: raise AnsibleError( "Incorrect format from the Scaleway API response") link = response.headers['Link'] if not link: return results relations = parse_pagination_link(link) if 'next' not in relations: return results paginated_url = urllib_parse.urljoin(paginated_url, relations['next'])
def run(self, terms, variables=None, **kwargs): self.set_options(direct=kwargs) ret = [] for term in terms: display.vvvv("url lookup connecting to %s" % term) try: response = open_url(term, validate_certs=self.get_option('validate_certs'), use_proxy=self.get_option('use_proxy'), url_username=self.get_option('username'), url_password=self.get_option('password'), headers=self.get_option('headers')) except HTTPError as e: raise AnsibleError("Received HTTP error for %s : %s" % (term, to_native(e))) except URLError as e: raise AnsibleError("Failed lookup url for %s : %s" % (term, to_native(e))) except SSLValidationError as e: raise AnsibleError("Error validating the server's certificate for %s: %s" % (term, to_native(e))) except ConnectionError as e: raise AnsibleError("Error connecting to %s: %s" % (term, to_native(e))) if self.get_option('split_lines'): for line in response.read().splitlines(): ret.append(to_text(line)) else: ret.append(to_text(response.read())) return ret
def _call(self, payload): self._id += 1 if 'id' not in payload: payload['id'] = self._id if 'jsonrpc' not in payload: payload['jsonrpc'] = '2.0' data = json.dumps(payload) try: resp = open_url(self._url, timeout=self._timeout, method='POST', data=data, headers=self._headers, validate_certs=self._validate_certs) if resp.code != 200: raise NsoException( 'NSO returned HTTP code {0}, expected 200'.format( resp.status), {}) except socket.timeout: raise NsoException( 'request timed out against NSO at {0}'.format(self._url), {}) resp_body = resp.read() resp_json = json.loads(resp_body) if 'error' in resp_json: self._handle_call_error(payload, resp_json) return resp, resp_json
def create_service(module, auth, template_id, service_name, custom_attrs, unique, wait, wait_timeout): # make sure that the values in custom_attrs dict are strings custom_attrs_with_str = dict((k, str(v)) for k, v in custom_attrs.items()) data = { "action": { "perform": "instantiate", "params": { "merge_template": { "custom_attrs_values": custom_attrs_with_str, "name": service_name } } } } try: response = open_url(auth.url + "/service_template/" + str(template_id) + "/action", method="POST", data=module.jsonify(data), force_basic_auth=True, url_username=auth.user, url_password=auth.password) except Exception as e: module.fail_json(msg=str(e)) service_result = module.from_json(response.read())["DOCUMENT"] return service_result
def run(self, terms, variables=None, **kwargs): self.set_options(direct=kwargs) ret = [] for term in terms: auth = to_text( base64.b64encode( to_bytes('{0}:{1}'.format(self.get_option('cpm_username'), self.get_option('cpm_password')), errors='surrogate_or_strict'))) if self.get_option('use_https') is True: protocol = "https://" else: protocol = "http://" if (term == 'temperature'): fullurl = ("%s%s/api/v2/status/temperature" % (protocol, self.get_option('cpm_url'))) elif (term == 'firmware'): fullurl = ("%s%s/api/v2/status/firmware" % (protocol, self.get_option('cpm_url'))) elif (term == 'status'): fullurl = ("%s%s/api/v2/status/status" % (protocol, self.get_option('cpm_url'))) elif (term == 'alarms'): fullurl = ("%s%s/api/v2/status/alarms" % (protocol, self.get_option('cpm_url'))) else: raise AnsibleError("Status command not recognized %s " % (term)) try: response = open_url( fullurl, validate_certs=self.get_option('validate_certs'), use_proxy=self.get_option('use_proxy'), headers={ 'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth }) except HTTPError as e: raise AnsibleError("Received HTTP error for %s : %s" % (fullurl, to_native(e))) except URLError as e: raise AnsibleError("Failed lookup url for %s : %s" % (fullurl, to_native(e))) except SSLValidationError as e: raise AnsibleError( "Error validating the server's certificate for %s: %s" % (fullurl, to_native(e))) except ConnectionError as e: raise AnsibleError("Error connecting to %s: %s" % (fullurl, to_native(e))) ret.append(to_text(response.read())) return ret
def memset_api_call(api_key, api_method, payload=None): ''' Generic function which returns results back to calling function. Requires an API key and an API method to assemble the API URL. Returns response text to be analysed. ''' # instantiate a response object response = Response() # if we've already started preloading the payload then copy it # and use that, otherwise we need to isntantiate it. if payload is None: payload = dict() else: payload = payload.copy() # set some sane defaults has_failed = False msg = None data = urlencode(payload) headers = {'Content-Type': 'application/x-www-form-urlencoded'} api_uri_base = 'https://api.memset.com/v1/json/' api_uri = '{0}{1}/'.format(api_uri_base, api_method) try: resp = open_url(api_uri, data=data, headers=headers, method="POST", force_basic_auth=True, url_username=api_key) response.content = resp.read().decode('utf-8') response.status_code = resp.getcode() except urllib_error.HTTPError as e: try: errorcode = e.code except AttributeError: errorcode = None has_failed = True response.content = e.read().decode('utf8') response.status_code = errorcode if response.status_code is not None: msg = "Memset API returned a {0} response ({1}, {2}).".format( response.status_code, response.json()['error_type'], response.json()['error']) else: msg = "Memset API returned an error ({0}, {1}).".format( response.json()['error_type'], response.json()['error']) if msg is None: msg = response.json() return (has_failed, msg, response)
def send_event(self, url, authtoken, state, result, runtime): if result._task_fields['args'].get('_ansible_check_mode') is True: self.ansible_check_mode = True if result._task_fields['args'].get('_ansible_version'): self.ansible_version = \ result._task_fields['args'].get('_ansible_version') if result._task._role: ansible_role = str(result._task._role) else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session data['status'] = state data['timestamp'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S ' '+0000') data['host'] = self.host data['ip_address'] = self.ip_address data['user'] = self.user data['runtime'] = runtime data['ansible_version'] = self.ansible_version data['ansible_check_mode'] = self.ansible_check_mode data['ansible_host'] = result._host.name data['ansible_playbook'] = self.ansible_playbook data['ansible_role'] = ansible_role data['ansible_task'] = result._task_fields data['ansible_result'] = result._result # This wraps the json payload in and outer json event needed by Splunk jsondata = json.dumps(data, cls=AnsibleJSONEncoder, sort_keys=True) jsondata = '{"event":' + jsondata + "}" open_url(url, jsondata, headers={ 'Content-type': 'application/json', 'Authorization': 'Splunk ' + authtoken }, method='POST')
def _send_annotation(self, annotation): try: response = open_url(self.grafana_url, data=json.dumps(annotation), headers=self.headers, method="POST", validate_certs=self.validate_grafana_certs, url_username=self.grafana_user, url_password=self.grafana_password, http_agent=self.http_agent, force_basic_auth=self.force_basic_auth) except Exception as e: self._display.error(u'Could not submit message to Grafana: %s' % to_text(e))
def user_add_to_group(module): # Get username, and groupname from module parameters, and api base url # along with validate_certs from the cyberark_session established username = module.params["username"] group_name = module.params["group_name"] cyberark_session = module.params["cyberark_session"] api_base_url = cyberark_session["api_base_url"] validate_certs = cyberark_session["validate_certs"] # Prepare result, end_point, headers and payload result = {} end_point = "/PasswordVault/WebServices/PIMServices.svc//Groups/{0}/Users".format( group_name) headers = {'Content-Type': 'application/json'} headers["Authorization"] = cyberark_session["token"] payload = {"UserName": username} try: # execute REST action response = open_url( api_base_url + end_point, method="POST", headers=headers, data=json.dumps(payload), validate_certs=validate_certs) result = {"result": {}} return (True, result, response.getcode()) except (HTTPError, httplib.HTTPException) as http_exception: exception_text = to_text(http_exception) if http_exception.code == 409 and "ITATS262E" in exception_text: # User is already member of Group return (False, None, http_exception.code) else: module.fail_json( msg=("Error while performing user_add_to_group." "Please validate parameters provided." "\n*** end_point=%s%s\n ==> %s" % (api_base_url, end_point, exception_text)), payload=payload, headers=headers, status_code=http_exception.code) except Exception as unknown_exception: module.fail_json( msg=("Unknown error while performing user_add_to_group." "\n*** end_point=%s%s\n%s" % (api_base_url, end_point, to_text(unknown_exception))), payload=payload, headers=headers, status_code=-1)
def _fetch_conjur_token(conjur_url, account, username, api_key): conjur_url = '{0}/authn/{1}/{2}/authenticate'.format(conjur_url, account, username) display.vvvv('Authentication request to Conjur at: {0}, with user: {1}'.format(conjur_url, username)) response = open_url(conjur_url, data=api_key, method='POST') code = response.getcode() if code != 200: raise AnsibleError('Failed to authenticate as \'{0}\' (got {1} response)' .format(username, code)) return response.read()
def get_all_templates(module, auth): try: all_templates = open_url(url=(auth.url + "/service_template"), method="GET", force_basic_auth=True, url_username=auth.user, url_password=auth.password) except Exception as e: module.fail_json(msg=str(e)) return module.from_json(all_templates.read())
def get_all_services(module, auth): try: response = open_url(auth.url + "/service", method="GET", force_basic_auth=True, url_username=auth.user, url_password=auth.password) except Exception as e: module.fail_json(msg=str(e)) return module.from_json(response.read())
def request(self, api, endpoint, *args, **kwargs): """ Send a request to API backend and pre-process a response. :param api: API to send a request to :type api: str :param endpoint: API endpoint to fetch data from :type endpoint: str :param args: other args for open_url :param kwargs: other kwargs for open_url :return: server response. JSON response is automatically deserialized. :rtype: dict | list | str """ default_headers = { 'Authorization': "Bearer {0}".format(self._token), 'Accept': "*/*" # Otherwise server doesn't set content-type header } url = self.base_url.format(api=api, endpoint=endpoint) headers = default_headers arg_headers = kwargs.pop('headers', None) if arg_headers: headers.update(arg_headers) try: display.vvvv('manifold lookup connecting to {0}'.format(url)) response = open_url(url, headers=headers, http_agent=self.http_agent, *args, **kwargs) data = response.read() if response.headers.get('content-type') == 'application/json': data = json.loads(data) return data except ValueError: raise ApiError( 'JSON response can\'t be parsed while requesting {url}:\n{json}' .format(json=data, url=url)) except HTTPError as e: raise ApiError( 'Server returned: {err} while requesting {url}:\n{response}'. format(err=str(e), url=url, response=e.read())) except URLError as e: raise ApiError('Failed lookup url for {url} : {err}'.format( url=url, err=str(e))) except SSLValidationError as e: raise ApiError( 'Error validating the server\'s certificate for {url}: {err}'. format(url=url, err=str(e))) except ConnectionError as e: raise ApiError('Error connecting to {url}: {err}'.format( url=url, err=str(e)))
def create_maintenance(auth_headers, url, statuspage, host_ids, all_infrastructure_affected, automation, title, desc, returned_date, maintenance_notify_now, maintenance_notify_72_hr, maintenance_notify_24_hr, maintenance_notify_1_hr): returned_dates = [[x] for x in returned_date] component_id = [] container_id = [] for val in host_ids: component_id.append(val['component_id']) container_id.append(val['container_id']) try: values = json.dumps({ "statuspage_id": statuspage, "components": component_id, "containers": container_id, "all_infrastructure_affected": str(int(all_infrastructure_affected)), "automation": str(int(automation)), "maintenance_name": title, "maintenance_details": desc, "date_planned_start": returned_dates[0], "time_planned_start": returned_dates[1], "date_planned_end": returned_dates[2], "time_planned_end": returned_dates[3], "maintenance_notify_now": str(int(maintenance_notify_now)), "maintenance_notify_72_hr": str(int(maintenance_notify_72_hr)), "maintenance_notify_24_hr": str(int(maintenance_notify_24_hr)), "maintenance_notify_1_hr": str(int(maintenance_notify_1_hr)) }) response = open_url(url + "/v2/maintenance/schedule", data=values, headers=auth_headers) data = json.loads(response.read()) if data["status"]["error"] == "yes": return 1, None, data["status"]["message"] except Exception as e: return 1, None, to_native(e) return 0, None, None
def send_event(self, url, state, result, runtime): if result._task_fields['args'].get('_ansible_check_mode') is True: self.ansible_check_mode = True if result._task_fields['args'].get('_ansible_version'): self.ansible_version = \ result._task_fields['args'].get('_ansible_version') if result._task._role: ansible_role = str(result._task._role) else: ansible_role = None if 'args' in result._task_fields: del result._task_fields['args'] data = {} data['uuid'] = result._task._uuid data['session'] = self.session data['status'] = state data['timestamp'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S ' '+0000') data['host'] = self.host data['ip_address'] = self.ip_address data['user'] = self.user data['runtime'] = runtime data['ansible_version'] = self.ansible_version data['ansible_check_mode'] = self.ansible_check_mode data['ansible_host'] = result._host.name data['ansible_playbook'] = self.ansible_playbook data['ansible_role'] = ansible_role data['ansible_task'] = result._task_fields data['ansible_result'] = result._result open_url(url, data=json.dumps(data, cls=AnsibleJSONEncoder, sort_keys=True), headers={ 'Content-type': 'application/json', 'X-Sumo-Host': data['ansible_host'] }, method='POST')
def run_module(): # define the available arguments/parameters that a user can pass to # the module module_args = dict( cpm_url=dict(type='str', required=True), cpm_username=dict(type='str', required=True), cpm_password=dict(type='str', required=True, no_log=True), port=dict(type='list', default=['*']), use_https=dict(type='bool', default=True), validate_certs=dict(type='bool', default=True), use_proxy=dict(type='bool', default=False) ) result = dict( changed=False, data='' ) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), errors='surrogate_or_strict'))) if module.params['use_https'] is True: protocol = "https://" else: protocol = "http://" ports = module.params['port'] if isinstance(ports, list): ports = ','.join(to_native(x) for x in ports) fullurl = ("%s%s/api/v2/config/serialports?ports=%s" % (protocol, to_native(module.params['cpm_url']), ports)) try: response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) except HTTPError as e: fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) module.fail_json(**fail_json) except URLError as e: fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) module.fail_json(**fail_json) except SSLValidationError as e: fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) module.fail_json(**fail_json) except ConnectionError as e: fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) module.fail_json(**fail_json) result['data'] = json.loads(response.read()) module.exit_json(**result)
def user_delete(module): # Get username from module parameters, and api base url # along with validate_certs from the cyberark_session established username = module.params["username"] cyberark_session = module.params["cyberark_session"] api_base_url = cyberark_session["api_base_url"] validate_certs = cyberark_session["validate_certs"] # Prepare result, end_point, and headers result = {} end_point = "/PasswordVault/WebServices/PIMServices.svc/Users/{0}".format( username) headers = {'Content-Type': 'application/json'} headers["Authorization"] = cyberark_session["token"] try: # execute REST action response = open_url( api_base_url + end_point, method="DELETE", headers=headers, validate_certs=validate_certs) result = {"result": {}} return (True, result, response.getcode()) except (HTTPError, httplib.HTTPException) as http_exception: exception_text = to_text(http_exception) if http_exception.code == 404 and "ITATS003E" in exception_text: # User does not exist result = {"result": {}} return (False, result, http_exception.code) else: module.fail_json( msg=("Error while performing user_delete." "Please validate parameters provided." "\n*** end_point=%s%s\n ==> %s" % (api_base_url, end_point, exception_text)), headers=headers, status_code=http_exception.code) except Exception as unknown_exception: module.fail_json( msg=("Unknown error while performing user_delete." "\n*** end_point=%s%s\n%s" % (api_base_url, end_point, to_text(unknown_exception))), headers=headers, status_code=-1)
def change_service_owner(module, auth, service_id, owner_id): data = {"action": {"perform": "chown", "params": {"owner_id": owner_id}}} try: status_result = open_url(auth.url + "/service/" + str(service_id) + "/action", method="POST", force_basic_auth=True, url_username=auth.user, url_password=auth.password, data=module.jsonify(data)) except Exception as e: module.fail_json(msg=str(e))
def load_configuration(self): if not os.path.isfile(self.src): self.module.fail_json( msg="Source file {0} does not exist".format(self.src)) url = self.host.configManager.firmwareSystem.QueryFirmwareConfigUploadURL( ) url = url.replace('*', self.host.name) # find manually the url if there is a redirect because urllib2 -per RFC- doesn't do automatic redirects for PUT requests try: request = open_url(url=url, method='HEAD', validate_certs=self.validate_certs) except HTTPError as e: url = e.geturl() try: with open(self.src, 'rb') as file: data = file.read() request = open_url(url=url, data=data, method='PUT', validate_certs=self.validate_certs, url_username=self.username, url_password=self.password, force_basic_auth=True) except Exception as e: self.module.fail_json(msg=to_native(e)) if not self.host.runtime.inMaintenanceMode: self.enter_maintenance() try: self.host.configManager.firmwareSystem.RestoreFirmwareConfiguration( force=True) self.module.exit_json(changed=True) except Exception as e: self.exit_maintenance() self.module.fail_json(msg=to_native(e))
def grafana_switch_organisation(self, headers): try: r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST') except HTTPError as e: raise GrafanaAPIException( 'Unable to switch to organization %s : %s' % (self.grafana_org_id, to_native(e))) if r.getcode() != 200: raise GrafanaAPIException( 'Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode())))