예제 #1
0
 def v2_runner_on_skipped(self, result):
     if ('no_print_skip_action' not in result._task.tags
             and 'no_print_action' not in result._task.tags
         ) or 'print_action' in result._task.tags or (
             self._display.verbosity > 1
             or '_ansible_verbose_always' in result._result):
         CallbackModule_default.v2_runner_on_skipped(self, result)
예제 #2
0
    def _dump_results(self, result):
        '''Return the text to output for a result.'''

        # Enable JSON identation
        result['_ansible_verbose_always'] = True

        save = {}
        for key in [
                'stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg',
                'module_stdout', 'module_stderr'
        ]:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        for key in [
                'stdout', 'stderr', 'msg', 'module_stdout', 'module_stderr'
        ]:
            if key in save and save[key]:
                output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

        for key, value in save.items():
            result[key] = value

        return output
예제 #3
0
 def test_callback(self):
     t = pyansible.Playbook('test.yml')
     from ansible.plugins.callback.default import CallbackModule
     cb = CallbackModule()
     t.callback = cb
     self.assertEqual(cb, t._tqm._stdout_callback)
     self.assertEqual(cb, t.callback)
예제 #4
0
    def _dump_results(self,
                      result,
                      indent=None,
                      sort_keys=True,
                      keep_invocation=False):
        '''Properly format JSON output.'''
        save = {}
        for key in [
                'stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg',
                'module_stdout', 'module_stderr'
        ]:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        for key in [
                'stdout', 'stderr', 'msg', 'module_stdout', 'module_stderr'
        ]:
            if key in save and save[key]:
                output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

        for key, value in save.items():
            result[key] = value

        return output
예제 #5
0
 def v2_runner_on_ok(self, result):
     host = result._host
     self.results[-1]['tasks'][-1]['hosts'][host.name] = result._result
     self.results[-1]['tasks'][-1]['hosts'][
         host.name]['epoch'] = time.time()
     self.module_filter(result)
     return CallbackModule_default.v2_runner_on_ok(self, result)
예제 #6
0
    def _dump_results(self, result):
        # Enable JSON identation
        result['_ansible_verbose_always'] = True

        save = {}
        # Reference for common return values:
        # https://docs.ansible.com/ansible/2.7/reference_appendices/common_return_values.html
        for key in [
                'stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg',
                'invocation'
        ]:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        # Exclude stdout_lines, stderr_lines in output.
        for key in ['stdout', 'stderr', 'msg']:
            if key in save and save[key]:
                output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

        # Deal with 'invocation'.
        if 'invocation' in save and save['invocation']:
            invocation = json.dumps(save['invocation'],
                                    indent=4)  # Pretty printed json.
            output += '\n\n%s:\n\n%s\n' % ('INVOCATION', invocation)

        for key, value in save.items():
            result[key] = value

        return output
예제 #7
0
 def v2_runner_on_failed(self, result, ignore_errors=False):
     host = result._host
     self.results[-1]['tasks'][-1]['hosts'][host.name] = result._result
     self.results[-1]['tasks'][-1]['hosts'][
         host.name]['epoch'] = time.time()
     return CallbackModule_default.v2_runner_on_failed(
         self, result, ignore_errors)
예제 #8
0
 def _dump_results(self,
                   result,
                   indent=None,
                   sort_keys=True,
                   keep_invocation=False):
     return CallbackModule_default._dump_results(self,
                                                 result,
                                                 indent=4,
                                                 sort_keys=True,
                                                 keep_invocation=False)
예제 #9
0
def main():
    display = Display(verbosity=settings.DEFAULT_ANSIBLE_VERBOSITY)
    results_callback = CallbackModule()
    results_callback._display = display
    loader = DataLoader()
    loader.set_basedir(basedir_2)

    # create inventory, use path to host config file as source
    # or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources='192.168.245.9,')

    # variable manager takes care of merging all the different sources
    # to give you a unifed view of variables available in each context
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    variable_manager.extra_vars = extra_vars_2
    play_source = loader.load_from_file(play_source_2)[0]
    # play_source['ansible_ssh_user'] = "******"
    # play_source['ansible_ssh_private_key_file'] = "/home/user/.ssh/id_rsa"

    # Create play object, playbook objects use .load instead of init or new methods,
    # this will also automatically create the task objects from the info provided in play_source
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords={},
            stdout_callback=results_callback,
        )
        result = tqm.run(play)
        print(result)
    finally:
        if tqm is not None:
            tqm.cleanup()

        # Remove ansible tmpdir
        shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
예제 #10
0
    def v2_playbook_on_stats(self, stats):
        """Display info about playbook statistics"""

        hosts = sorted(stats.processed.keys())
        filename = os.getenv('ANSIBLE_REPORT_FILE', "report.json")
        fileout = open(filename, "w")
        summary = {}
        for h in hosts:
            s = stats.summarize(h)
            summary[h] = s
        output = {'plays': self.results, 'stats': summary}
        fileout.write(json.dumps(output, indent=4, sort_keys=True))
        #self._display.display(json.dumps(output, indent=4, sort_keys=True),stderr=True)
        #self._display.display(json.dumps(self.results, indent=4, sort_keys=True),stderr=True)
        if self.db:
            self.db.commit()
            self.db.close()
        return CallbackModule_default.v2_playbook_on_stats(self, stats)
예제 #11
0
    def _dump_results(self, result):
        '''Return the text to output for a result.'''

        result['_ansible_verbose_always'] = True

        save = {}
        for key in ['stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg', 'module_stdout', 'module_stderr']:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        for key in ['stdout', 'stderr', 'msg', 'module_stdout', 'module_stderr']:
            if key in save and save[key]:
                output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

        for key, value in save.items():
            result[key] = value

        return output
예제 #12
0
    def _dump_results(self, result, indent=None, sort_keys=True, keep_invocation=False):
        '''Return the text to output for a result.'''

        # Enable JSON identation
        result['_ansible_verbose_always'] = True

        save = {}
        for key in ['stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg', 'module_stdout', 'module_stderr']:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        for key in ['stdout', 'stderr', 'msg', 'module_stdout', 'module_stderr']:
            if key in save and save[key]:
                output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

        for key, value in save.items():
            result[key] = value

        return output
예제 #13
0
    def run_playbook(self, filenames, vars):
        """
        run ansible_service palybook
        """
        try:
            self.callback = ResultsCollector()

            extra_vars = vars
            self.variable_manager.extra_vars = extra_vars
            # actually run it
            executor = PlaybookExecutor(
                playbooks=filenames,
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            # executor._tqm._stdout_callback = self.callback
            executor._tqm._stdout_callback = CallbackModule()
            executor.run()

        except Exception as e:
            print("error:", e.message)
예제 #14
0
 def v2_playbook_on_play_start(self, play):
     self.results.append(self._new_play(play))
     return CallbackModule_default.v2_playbook_on_play_start(self, play)
예제 #15
0
 def __init__(self):
     self.results = []
     return CallbackModule_default.__init__(self)
예제 #16
0
 def v2_runner_on_unreachable(self, result):
     host = result._host
     self.results[-1]['tasks'][-1]['hosts'][host.name] = result._result
     self.results[-1]['tasks'][-1]['hosts'][
         host.name]['epoch'] = time.time()
     return CallbackModule_default.v2_runner_on_unreachable(self, result)
예제 #17
0
 def v2_runner_item_on_ok(self, result):
     if 'no_print_action' not in result._task.tags or 'print_action' in result._task.tags or (
             self._display.verbosity > 1
             or '_ansible_verbose_always' in result._result):
         CallbackModule_default.v2_runner_item_on_ok(self, result)
예제 #18
0
 def v2_playbook_on_include(self, included_file):
     if not included_file._filename.endswith(
             'async_job_watcher/tasks/recursive.yml'
     ) and not included_file._filename.endswith(
             'async_job_watcher/tasks/end.yml'):
         CallbackModule_default.v2_playbook_on_include(self, included_file)
예제 #19
0
def main():
    variable_manager = VariableManager()
    loader = DataLoader()
    passwd = None
    become_passwd = None
    display = Display()

    parser = argparse.ArgumentParser()
    prepare_parser(parser)
    args = parser.parse_args()
    if args.askpass:
        passwd = getpass.getpass("SSH password:"******"BECOME password "
                                        "[defaults to SSH password]:")
        if become_passwd == "":
            become_passwd = passwd

    options = Options(
        connection=args.connection,
        module_path=args.module_path,
        forks=args.forks,
        become=args.become,
        become_method=args.become_method,
        become_user=args.become_user,
        check=args.check,
        remote_user=args.remote_user,
        private_key_file=args.private_key_file,
        ssh_common_args=None,
        sftp_extra_args=None,
        scp_extra_args=None,
        ssh_extra_args=None,
        verbosity=args.verbose
    )

    display.verbosity = args.verbose
    cb = CallbackModule(display)
    if not os.path.isfile(args.inventory):
        exit("ERROR! Can't open host list")

    inventory = Inventory(
        loader=loader,
        variable_manager=variable_manager,
        host_list=args.inventory
    )

    inventory.subset(args.subset)

    play_source = dict(
        name="Assign roles %s" % args.roles,
        hosts='all',
        gather_facts='no',
        roles=args.roles)

    variable_manager.set_inventory(inventory)
    play = Play().load(
        play_source,
        variable_manager=variable_manager,
        loader=loader
    )

    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords={'conn_pass': passwd, 'become_pass': become_passwd},
            stdout_callback=cb
        )
        tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
예제 #20
0
 def __init__(self, *args, **kwargs):
     CallbackModule_default.__init__(self, *args, **kwargs)
     self.__handlers = {}
예제 #21
0
    def _dump_results(self,
                      result,
                      indent=None,
                      sort_keys=True,
                      keep_invocation=False):
        '''Return the text to output for a result.'''

        # Enable JSON identation
        result['_ansible_verbose_always'] = True

        save = {}
        for key in [
                'stdout', 'stdout_lines', 'stderr', 'stderr_lines', 'msg',
                'log', 'module_stdout', 'module_stderr'
        ]:
            if key in result:
                save[key] = result.pop(key)

        output = CallbackModule_default._dump_results(self, result)

        print("\e[31m Hello world \e[0m")

        CRED = '\033[91m'
        CEND = '\033[0m'
        content = ''

        for key in [
                'stdout', 'stderr', 'msg', 'log', 'module_stdout',
                'module_stderr'
        ]:
            if key in save and save[key]:
                if key == 'log':
                    # print("this key is log")
                    # print(save[key])
                    lines = save[key].split('\n')
                    for line in lines:

                        if operator.contains(line.lower(), "text"):
                            data = line.lower().split(" text: ")
                            content += '\n' + data[0]

                            json_object = json.loads(data[1])
                            # json_formatted_str = json.dumps(json_object, indent=2)
                            formatted_json = json.dumps(json_object,
                                                        sort_keys=True,
                                                        indent=4)
                            colorful_json = highlight(
                                formatted_json, lexers.JsonLexer(),
                                formatters.TerminalFormatter())
                            content += '\n' + CRED + "Text:" + CEND
                            content += '\n' + CRED + colorful_json + CEND + '\n'

                        elif operator.contains(line.lower(), "headers are:"):
                            data = line.lower().split(" headers are: ")
                            content += '\n' + data[0]
                            content += '\n' + CRED + "Headers are:" + CEND
                            content += '\n' + CRED + data[1] + CEND + '\n'

                        elif operator.contains(line.lower(), "input data:"):
                            data = line.lower().split(" input data: ")
                            content += '\n' + data[0]
                            content += '\n' + CRED + "Input Data:" + CEND
                            content += '\n' + CRED + data[1] + CEND + '\n'

                        else:
                            content += '\n' + line

                    # add content to output:
                    output += '\n\n%s:\n\n%s\n' % (key.upper(), content)
                else:
                    # print("this key issnt log")
                    output += '\n\n%s:\n\n%s\n' % (key.upper(), save[key])

            # logging.warning(output)

        for key, value in save.items():
            result[key] = value

        return output
예제 #22
0
 def v2_playbook_on_task_start(self, task, is_conditional):
     self.results[-1]['tasks'].append(self._new_task(task))
     return CallbackModule_default.v2_playbook_on_task_start(
         self, task, is_conditional)
예제 #23
0
 def __init__(self, *args, **kwargs):
     CallbackModule_default.__init__(self, *args, **kwargs)
     self.__handlers = {}
예제 #24
0
 def v2_playbook_on_task_start(self, task, is_conditional):
     if (not task.get_name().strip().endswith('no_print_action')
             and 'no_print_action' not in task.tags
         ) or 'print_action' in task.tags or self._display.verbosity > 1:
         CallbackModule_default.v2_playbook_on_task_start(
             self, task, is_conditional)