def _handle_ns_map(self): try: ns_map_src = self._task.args.get('ns_map') except Exception as exc: display.vvvv('No ns_map is specified') return dict(failed=False, msg="No ns map is specified") if ns_map_src == None: return working_path = self._get_working_path() if os.path.isabs(ns_map_src) or urlsplit('ns_map_src').scheme: ns_map_file = ns_map_src else: ns_map_file = self._loader.path_dwim_relative(working_path, 'templates', ns_map_src) if not ns_map_file: ns_map_file = self._loader.path_dwim_relative(working_path, ns_map_src) if not os.path.exists(ns_map_file): raise ValueError('path specified in ns_map not found') try: with open(ns_map_file, 'r') as f: ns_map_data = yaml.load(f) q(ns_map_data) return (ns_map_data) except IOError: return dict(failed=True, msg='unable to load ns_map file')
def _handle_template(self): src = self._task.args.get('src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise ValueError('path specified in src not found') try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError: return dict(failed=True, msg='unable to load src file') # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data)
def split_url(value, query='', alias='urlsplit'): """ This same function will be available from Ansible 2.4 with this same interface. For more information see: https://docs.ansible.com/ansible/devel/playbooks_filters.html#url-split-filter """ url = urlsplit(value) results = { 'hostname': url.hostname, 'netloc': url.netloc, 'username': url.username, 'password': url.password, 'path': url.path, 'port': url.port, 'scheme': url.scheme, 'query': url.query, 'fragment': url.fragment } if query: if query not in results: raise AnsibleFilterError(alias + ': unknown URL component: %s' % query) return results[query] else: return results
def _handle_src_option(self, convert_data=True): src = self._task.args.get('src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise AnsibleError('path specified in src not found') try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError as e: raise AnsibleError("unable to load src file {0}, I/O error({1}): {2}".format(source, e.errno, e.strerror)) # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data, convert_data=convert_data)
def _handle_dest_path(self, dest): working_path = self._get_working_path() if os.path.isabs(dest) or urlsplit('dest').scheme: dst = dest else: dst = self._loader.path_dwim_relative(working_path, '', dest) return dst
def url_get(module, url, timeout=10, headers=None): """ Download data from the url and store in a temporary file. Return (tempfile, info about the request) """ if module.check_mode: method = 'HEAD' else: method = 'GET' rsp, info = fetch_url(module, url, timeout=timeout, headers=headers, method=method) if info['status'] == 304: module.exit_json(url=url, changed=False, msg=info.get('msg', '')) # Exceptions in fetch_url may result in a status -1, # the ensures a proper error to the user in all cases if info['status'] == -1: module.fail_json(msg=info['msg'], url=url) if info['status'] != 200 and not url.startswith('file:/') and not ( url.startswith('ftp:/') and info.get('msg', '').startswith('OK')): module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], url=url) tmp_dest = module.tmpdir fd, tempname = tempfile.mkstemp(dir=tmp_dest) f = os.fdopen(fd, 'wb') try: shutil.copyfileobj(rsp, f) except Exception as e: os.remove(tempname) module.fail_json(msg="failed to create temporary content file: %s" % to_native(e), exception=traceback.format_exc()) f.close() rsp.close() fn = os.path.basename(urlsplit(url)[2]) if fn == '': os.remove(tempname) module.fail_json(msg="Request failed. Can't detect filename in url.", url=url) dest = os.path.join(tmp_dest, fn) module.atomic_move(tempname, dest) return dest, info
def split_url(value, query='', alias='urlsplit'): results = helpers.object_to_dict(urlsplit(value), exclude=['count', 'index', 'geturl', 'encode']) # If a query is supplied, make sure it's valid then return the results. # If no option is supplied, return the entire dictionary. if query: if query not in results: raise AnsibleFilterError(alias + ': unknown URL component: %s' % query) return results[query] else: return results
def _get_binary_src_file(self, src): working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise ValueError('path specified in src not found') return source
def absolute_location(url, location): """Attempts to create an absolute URL based on initial URL, and next URL, specifically in the case of a ``Location`` header. """ if '://' in location: return location elif location.startswith('/'): parts = urlsplit(url) base = url.replace(parts[2], '') return '%s%s' % (base, location) elif not location.startswith('/'): base = os.path.dirname(url) return '%s/%s' % (base, location) else: return location
def url_filename(url): fn = os.path.basename(urlsplit(url)[2]) if fn == '': return 'index.html' return fn
def is_url(checksum): """ Returns True if checksum value has supported URL scheme, else False.""" supported_schemes = ('http', 'https', 'ftp', 'file') return urlsplit(checksum).scheme in supported_schemes