def main(): argument_spec = dict(all=dict(type='bool', default=False), ) # We are not going to raise an error here because the __init__ method of TowerAWXKitModule will do that for us if HAS_EXPORTABLE_RESOURCES: for resource in EXPORTABLE_RESOURCES: argument_spec[resource] = dict(type='str') module = TowerAWXKitModule(argument_spec=argument_spec) if not HAS_EXPORTABLE_RESOURCES: module.fail_json( msg="Your version of awxkit does not have import/export") # The export process will never change a Tower system module.json_output['changed'] = False # The exporter code currently works like the following: # Empty string == all assets of that type # Non-Empty string = just one asset of that type (by name or ID) # Asset type not present or None = skip asset type (unless everything is None, then export all) # Here we are going to setup a dict of values to export export_args = {} for resource in EXPORTABLE_RESOURCES: if module.params.get('all') or module.params.get(resource) == 'all': # If we are exporting everything or we got the keyword "all" we pass in an empty string for this asset type export_args[resource] = '' else: # Otherwise we take either the string or None (if the parameter was not passed) to get one or no items export_args[resource] = module.params.get(resource) # Currently the export process does not return anything on error # It simply just logs to Python's logger # Set up a log gobbler to get error messages from export_assets log_capture_string = StringIO() ch = logging.StreamHandler(log_capture_string) for logger_name in ['awxkit.api.pages.api', 'awxkit.api.pages.page']: logger = logging.getLogger(logger_name) logger.setLevel(logging.ERROR) ch.setLevel(logging.ERROR) logger.addHandler(ch) log_contents = '' # Run the export process try: module.json_output['assets'] = module.get_api_v2_object( ).export_assets(**export_args) module.exit_json(**module.json_output) except Exception as e: module.fail_json(msg="Failed to export assets {0}".format(e)) finally: # Finally, consume the logs in case there were any errors and die if there were log_contents = log_capture_string.getvalue() log_capture_string.close() if log_contents != '': module.fail_json(msg=log_contents)
def to_ini(o): if not isinstance(o, MutableMapping): raise AnsibleFilterError('to_ini requires a dict, got %s' % type(o)) data = copy.deepcopy(o) defaults = configparser.RawConfigParser(data.pop('DEFAULT', {})) parser = configparser.RawConfigParser() parser.optionxform = partial(to_text, errors='surrogate_or_strict') for section, items in data.items(): parser.add_section(section) for k, v in items.items(): parser.set(section, k, v) out = StringIO() defaults.write(out) parser.write(out) return out.getvalue().rstrip()
def to_ldif(cls, data): """Convert list of dictionary to LDIF.""" """See https://github.com/atterdag/ansible-filters-ldif for how to format dictionary. """ if isinstance(data, list): try: ldif_data = StringIO() ldif_writer = LDIFWriter(ldif_data) for entry in data: ldif_writer.unparse(str(entry[0]), cls.encode_values(dict(entry[1]))) return ldif_data.getvalue() except Exception: raise AnsibleFilterError( 'Invalid input data for to_ldif filter (%s)' % data) else: raise AnsibleFilterError( 'Input data to_ldif filter is not a list(%s)' % data)
def _do_it(self, action): master, slave = pty.openpty() p = subprocess.Popen(["ansible-connection"], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdin = os.fdopen(master, 'wb', 0) os.close(slave) src = StringIO() cPickle.dump(self._play_context.serialize(), src) stdin.write(src.getvalue()) src.close() stdin.write(b'\n#END_INIT#\n') stdin.write(to_bytes(action)) stdin.write(b'\n\n') stdin.close() (stdout, stderr) = p.communicate() return (p.returncode, stdout, stderr)
def receive(self, obj=None): recv = StringIO() handled = False self._matched_prompt = None while True: data = self._shell.recv(256) recv.write(data) recv.seek(recv.tell() - 256) window = self._strip(recv.read()) if obj and (obj.get('prompt') and not handled): handled = self._handle_prompt(window, obj) if self._find_prompt(window): self._last_response = recv.getvalue() resp = self._strip(self._last_response) return self._sanitize(resp, obj)
def _do_it(self, action): master, slave = pty.openpty() p = subprocess.Popen(["ansible-connection"], stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdin = os.fdopen(master, 'wb', 0) os.close(slave) src = StringIO() cPickle.dump(self._play_context.serialize(), src) stdin.write(src.getvalue()) src.close() stdin.write(b'\n#END_INIT#\n') stdin.write(to_bytes(action)) stdin.write(b'\n\n') stdin.close() (stdout, stderr) = p.communicate() return (p.returncode, stdout, stderr)
def main(): argument_spec = dict(assets=dict(type='dict', required=True)) module = ControllerAWXKitModule(argument_spec=argument_spec, supports_check_mode=False) assets = module.params.get('assets') if not HAS_EXPORTABLE_RESOURCES: module.fail_json( msg="Your version of awxkit does not appear to have import/export") # Currently the import process does not return anything on error # It simply just logs to Python's logger # Set up a log gobbler to get error messages from import_assets logger = logging.getLogger('awxkit.api.pages.api') logger.setLevel(logging.ERROR) log_capture_string = StringIO() ch = logging.StreamHandler(log_capture_string) ch.setLevel(logging.ERROR) logger.addHandler(ch) log_contents = '' # Run the import process try: module.json_output['changed'] = module.get_api_v2_object( ).import_assets(assets) except Exception as e: module.fail_json(msg="Failed to import assets {0}".format(e)) finally: # Finally, consume the logs in case there were any errors and die if there were log_contents = log_capture_string.getvalue() log_capture_string.close() if log_contents != '': module.fail_json(msg=log_contents) module.exit_json(**module.json_output)
def receive(self, cmd=None): recv = StringIO() handled = False while True: data = self.shell.recv(200) recv.write(data) recv.seek(recv.tell() - 200) window = self.strip(recv.read()) if hasattr(cmd, 'prompt') and not handled: handled = self.handle_prompt(window, cmd) try: if self.find_prompt(window): resp = self.strip(recv.getvalue()) return self.sanitize(cmd, resp) except ShellError: exc = get_exception() exc.command = cmd raise
def receive(self, cmd=None): recv = StringIO() handled = False while True: data = self.shell.recv(200) recv.write(data) recv.seek(recv.tell() - 200) window = self.strip(recv.read()) if hasattr(cmd, 'prompt') and not handled: handled = self.handle_prompt(window, cmd) try: if self.find_prompt(window): resp = self.strip(recv.getvalue()) return self.sanitize(cmd, resp) except ShellError: exc = get_exception() exc.command = cmd raise
def receive(self, obj=None): """Handles receiving of output from command""" recv = StringIO() handled = False self._matched_prompt = None while True: data = self._shell.recv(256) recv.write(data) offset = recv.tell() - 256 if recv.tell() > 256 else 0 recv.seek(offset) window = self._strip(recv.read()) if obj and (obj.get('prompt') and not handled): handled = self._handle_prompt(window, obj) if self._find_prompt(window): self._last_response = recv.getvalue() resp = self._strip(self._last_response) return self._sanitize(resp, obj)