示例#1
0
    def run_adhoc(self, host_list, module_name, module_args):
        play_source = dict(
            name="adhoc",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))]
        )

        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
        self.callback = ResultCallback()
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )

            tqm._stdout_callback = self.callback
            tqm.run(play)
        except Exception as err:
            raise Exception(err)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#2
0
    def run(self):
        """
        运行ansible任务.

        """
        # create play with tasks
        play_source = dict(name="Ansible Play",
                           hosts=self.ip_list,
                           gather_facts='no',
                           tasks=[
                               dict(action=dict(module=self.module_name,
                                                args=self.module_args))
                           ])
        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)

        # 运行
        tqm = None
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback='default',
            )
            tqm._stdout_callback = self.callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
        return result
示例#3
0
    def run(self, host_list, module_name, module_args, ):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        play_source = dict(
            name="Ansible Ad-hoc Command",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))]
        )
        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)

        tqm = None
        self.callback = ResultsCollector()
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback='default',
            )
            tqm._stdout_callback = self.callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#4
0
 def run_module(self, host_list, module_name, module_args):
     """
     :param host_list: ßß
     :param module_name: ansible 模块名称 (-m)
     :param module_args: ansible 模块参数 (-a)
     :return:
     """
     self.callback = ModuleResultsCollector()
     play_source = dict(
         name="Ansible Ad-hoc",
         hosts=host_list,
         gather_facts=self.gather_facts,
         tasks=[dict(action=dict(module=module_name, args=module_args))])
     play = Play().load(play_source,
                        loader=self.loader,
                        variable_manager=self.variable_manager)
     tqm = None
     try:
         tqm = TaskQueueManager(inventory=self.inventory,
                                variable_manager=self.variable_manager,
                                loader=self.loader,
                                options=self.options,
                                passwords=self.passwords,
                                stdout_callback=self.callback)
         tqm._stdout_callback = self.callback
         C.HOST_KEY_CHECKING = False  # 关闭第一次使用ansible连接客户端是输入命令
         tqm.run(play)
     except Exception as err:
         print err
     finally:
         if tqm is not None:
             tqm.cleanup()
         if self.loader:
             self.loader.cleanup_all_tmp_files()
示例#5
0
 def run_model(self, host_list, module_name, module_args):  
     """ 
     run module from andible ad-hoc. 
     module_name: ansible module_name 
     module_args: ansible module args 
     """  
     play_source = dict(  
             name="Ansible Play",  
             hosts=host_list,  
             gather_facts='no',  
             tasks=[dict(action=dict(module=module_name, args=module_args))]  
     )
      
     play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)  
     tqm = None  
     if self.redisKey or self.logId:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)  
     else:self.callback = ModelResultsCollector()  
     try:  
         tqm = TaskQueueManager(  
                 inventory=self.inventory,  
                 variable_manager=self.variable_manager,  
                 loader=self.loader,  
                 options=self.options,  
                 passwords=self.passwords,  
         )  
         tqm._stdout_callback = self.callback  
         constants.HOST_KEY_CHECKING = False #关闭第一次使用ansible连接客户端是输入命令
         tqm.run(play)  
     except Exception as err: 
         if self.redisKey:DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err)
         if self.logId:AnsibleSaveResult.Model.insert(self.logId, err)              
     finally:  
         if tqm is not None:  
             tqm.cleanup()  
示例#6
0
    def run(self, host_list, module_name, module_args,):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        # create play with tasks
        play_source = dict(
                name="Ansible Play",
                hosts=host_list,
                gather_facts='no',
                tasks=[dict(action=dict(module=module_name, args=module_args))]
        )
        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)

        # actually run it
        tqm = None
        self.callback = ResultsCollector()
        try:
            tqm = TaskQueueManager(
                    inventory=self.inventory,
                    variable_manager=self.variable_manager,
                    loader=self.loader,
                    options=self.options,
                    passwords=self.passwords,
            )
            tqm._stdout_callback = self.callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#7
0
    def _run(self, play):
        """
        run a tasksqueue manager
        """

        self.inventory = Inventory(loader=self.loader,
                                   variable_manager=self.variable_manager,
                                   host_list=self.hosts)
        self.variable_manager.set_inventory(self.inventory)

        tqm = None
        self.callback = ResultsCollector()

        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.password,
            )
            tqm._stdout_callback = self.callback
            self.result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#8
0
    def run(self, host_list, module_name, module_args):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        # create play with tasks
        play_source = dict(
            name="Ansible Play",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))])
        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)

        # actually run it
        tqm = None
        self.callback = AnsibleTaskResultCallback()
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            tqm._stdout_callback = self.callback
            tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#9
0
    def run_model(self, host_list, module_name, module_args):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        play_source = dict(
            name="Ansible Play",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))])

        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)
        tqm = None
        self.callback = ModelResultsCollector()
        import traceback
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback="minimal",
            )
            tqm._stdout_callback = self.callback
            constants.HOST_KEY_CHECKING = False
            tqm.run(play)
        except Exception as err:
            print(traceback.print_exc())
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#10
0
def ping(host_list):
    C.HOST_KEY_CHECKING = False
    loader = DataLoader()
    options = Options(connection='smart',forks=5,remote_user='******',ssh_common_args='-C -o ControlPersist=30s')
    passwords = dict()
    sources = host_list[0] + ','
    inventory = InventoryManager(loader=loader,sources=sources)
    variable_manager = VariableManager(loader=loader,inventory=inventory)
    play_source = dict(
        name = 'Test Ping',
        hosts = host_list,
        gather_facts = 'no',
        tasks = [dict(action=dict(module='ping',args=''))]
    )
    play = Play().load(play_source,variable_manager=variable_manager,loader=loader)
    tqm = None
    callback = ResultCollector()
    try:
        tqm = TaskQueueManager(
            inventory = inventory,
            variable_manager = variable_manager,
            loader = loader,
            options = options,
            passwords = passwords
        )
        tqm._stdout_callback = callback
        res = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
    return callback.result
示例#11
0
 def run_module(self, module_name, module_args, hosts=None):
     play_source = dict(name="Run Module",
                        hosts=hosts,
                        gather_facts='no',
                        tasks=[
                            {
                                "action": {
                                    "module": module_name,
                                    "args": module_args
                                }
                            },
                        ])
     play = Play().load(play_source,
                        variable_manager=self._variable_manager,
                        loader=self._loader)
     tqm = None
     self.callback = ResuCallbackModule()
     try:
         tqm = TaskQueueManager(
             inventory=self._inventory,
             variable_manager=self._variable_manager,
             loader=self._loader,
             passwords=self._passwords,
         )
         tqm._stdout_callback = self.callback
         tqm.run(play)
     finally:
         if tqm is not None:
             tqm.cleanup()
         # 这个临时目录会在 ~/.ansible/tmp/ 目录下
         shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
示例#12
0
 def run_model(self, host_list, module_name, module_args):
     """
     执行andible ad-hoc模块
     module_name: 模块名
     module_args: 模块参数
     """
     play_source = dict(
         name="Ansible Play",
         hosts=host_list,
         gather_facts='no',
         tasks=[dict(action=dict(module=module_name, args=module_args))]
     )
     # 创建play对象
     play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
     tqm = None
     # 创建结果收集对象
     self.callback = ModelResultsCollector()
     try:
         tqm = TaskQueueManager(
             inventory=self.inventory,
             variable_manager=self.variable_manager,
             loader=self.loader,
             options=self.options,
             passwords=self.passwords,
         )
         tqm._stdout_callback = self.callback
         result = tqm.run(play)
     finally:
         if tqm is not None:
             tqm.cleanup()
示例#13
0
    def run_model(self, host_list, module_name, module_args):
        self.callback = AdHoccallback(self.websocket, self.mysql)
        play_source = dict(
            name="Ansible Ad-hoc",
            hosts=host_list,
            gather_facts=self.gather_facts,
            tasks=[dict(action=dict(module=module_name, args=module_args))])
        play = Play().load(play_source,
                           loader=self.loader,
                           variable_manager=self.variable_manager)
        tqm = None
        try:
            tqm = TaskQueueManager(inventory=self.inventory,
                                   variable_manager=self.variable_manager,
                                   loader=self.loader,
                                   options=self.options,
                                   passwords=self.passwords,
                                   stdout_callback=self.callback)
            tqm._stdout_callback = self.callback
            constants.HOST_KEY_CHECKING = False  #关闭第一次使用ansible连接客户端是输入命令

            tqm.run(play)
        except Exception as err:
            logger.error(msg="run model failed: {err}".format(err=str(err)))
            if self.websocket: self.websocket.send(str(err))
        finally:
            if tqm is not None:
                tqm.cleanup()
            if self.loader:
                self.loader.cleanup_all_tmp_files()
示例#14
0
 def run_model(self, host_list, module_name, module_args):  
     """ 
     run module from andible ad-hoc. 
     module_name: ansible module_name 
     module_args: ansible module args 
     """  
     play_source = dict(  
             name="Ansible Play",  
             hosts=host_list,  
             gather_facts='no',  
             tasks=[dict(action=dict(module=module_name, args=module_args))]  
     )  
     play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)  
     tqm = None  
     if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)  
     else:self.callback = ModelResultsCollector()  
     try:  
         tqm = TaskQueueManager(  
                 inventory=self.inventory,  
                 variable_manager=self.variable_manager,  
                 loader=self.loader,  
                 options=self.options,  
                 passwords=self.passwords,  
         )  
         tqm._stdout_callback = self.callback  
         tqm.run(play)  
     finally:  
         if tqm is not None:  
             tqm.cleanup()  
示例#15
0
 def run_model(self, host_list, module_name, module_args):
     """
     ansible group1 -m shell -a 'ls /tmp'
     """
     self.callback = ADhocCallback()
     play_source = dict(
         name="Ansible Play",
         hosts=host_list,
         gather_facts='no',
         tasks=[dict(action=dict(module=module_name, args=module_args))])
     play = Play().load(play_source,
                        variable_manager=self.variable_manager,
                        loader=self.loader)
     tqm = None
     try:
         tqm = TaskQueueManager(
             inventory=self.inventory,
             variable_manager=self.variable_manager,
             loader=self.loader,
             options=self.options,
             passwords=self.passwords,
             stdout_callback="minimal",
         )
         tqm._stdout_callback = self.callback
         constants.HOST_KEY_CHECKING = False  #关闭第一次使用ansible连接客户端是输入命令
         tqm.run(play)
         self.results_raw = self.callback.result_row
     except Exception as err:
         print(err)
     finally:
         if tqm is not None:
             tqm.cleanup()
示例#16
0
 def run_model(self, host_list, module_name, module_args):
     """ 
     run module from andible ad-hoc. 
     module_name: ansible module_name 
     module_args: ansible module args 
     """
     play_source = dict(
         name="Ansible Play",
         hosts=host_list,
         gather_facts='no',
         tasks=[dict(action=dict(module=module_name, args=module_args))])
     play = Play().load(play_source,
                        variable_manager=self.variable_manager,
                        loader=self.loader)
     tqm = None
     if self.redisKey:
         self.callback = ModelResultsCollectorToSave(
             self.redisKey, self.logId)
     else:
         self.callback = ModelResultsCollector()
     try:
         tqm = TaskQueueManager(
             inventory=self.inventory,
             variable_manager=self.variable_manager,
             loader=self.loader,
             options=self.options,
             passwords=self.passwords,
         )
         tqm._stdout_callback = self.callback
         tqm.run(play)
     finally:
         if tqm is not None:
             tqm.cleanup()
示例#17
0
 def run_model(self):
     for task in self.taskinfo:
         play_source = dict(name="andible_api_play",
                            hosts=self.host_list,
                            gather_facts="no",
                            tasks=[
                                dict(action=dict(module=task.get("module"),
                                                 args=task.get("args")))
                            ])
         play = Play().load(play_source,
                            variable_manager=self.variable_manager,
                            loader=self.loader)
         tqm = None
         self.callback = ModelResultsCollector()
         try:
             tqm = TaskQueueManager(
                 inventory=self.inventory,
                 variable_manager=self.variable_manager,
                 loader=self.loader,
                 options=self.options,
                 passwords=self.passwords,
                 stdout_callback="minimal",
             )
             tqm._stdout_callback = self.callback
             result = tqm.run(play)
         except Exception as err:
             import traceback
             print(traceback.print_exc())
         finally:
             if tqm is not None:
                 tqm.cleanup()
def run_modules(host, module, args, options):

    task_list = [
        dict(action=dict(module='%s' % module, args='%s' % args)),
    ]

    play_source = dict(name="Ansible Ad-Hoc",
                       hosts=host,
                       gather_facts="no",
                       tasks=task_list)

    play = Play().load(play_source,
                       variable_manager=variable_manager,
                       loader=loader)
    tqm = None
    callback = ResultsCollector()

    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=None,
            run_tree=False,
        )
        tqm._stdout_callback = callback
        tqm.run(play)
        return AnsibleReturn(callback).result

    finally:
        if tqm is not None:
            tqm.cleanup()
示例#19
0
 def run_model(self, host_list, module_name, module_args):  
     """ 
     run module from andible ad-hoc. 
     module_name: ansible module_name 
     module_args: ansible module args 
     """  
     play_source = dict(  
             name="Ansible Play",  
             hosts=host_list,  
             gather_facts='no',  
             tasks=[dict(action=dict(module=module_name, args=module_args))]  
     )
      
     play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)  
     tqm = None  
     if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)  
     else:self.callback = ModelResultsCollector()  
     try:  
         tqm = TaskQueueManager(  
                 inventory=self.inventory,  
                 variable_manager=self.variable_manager,  
                 loader=self.loader,  
                 options=self.options,  
                 passwords=self.passwords,  
         )  
         tqm._stdout_callback = self.callback  
         constants.HOST_KEY_CHECKING = False #关闭第一次使用ansible连接客户端是输入命令
         tqm.run(play)  
     except Exception as err: 
         DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err)
         if self.logId:AnsibleSaveResult.Model.insert(self.logId, err)              
     finally:  
         if tqm is not None:  
             tqm.cleanup()  
示例#20
0
    def run(self, hosts, module_name, module_args):
        """ 
        run module from andible ad-hoc. 
        module_name: ansible module_name 
        module_args: ansible module args 
        """
        # create play with tasks
        play_source = dict(
            name="Ansible Play",
            hosts=hosts,
            gather_facts='no',
            #tasks = [dict(action=dict(module='shell', args='ls'), register='shell_out'),
            #    dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))]
            tasks=[dict(action=dict(module=module_name, args=module_args))])
        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)

        # actually run it
        tqm = None
        self.callback = ResultsCollector()
        #self.callback = ResultCallback()
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            tqm._stdout_callback = self.callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#21
0
    def run_model(self, host_list, module_name, module_args):
        if self.redisKey or self.logId:
            self.callback = ModelResultsCollectorToSave(
                self.redisKey, self.logId)
        else:
            self.callback = ModelResultsCollector()

        play_source = dict(
            name="Ansible Ad-hoc",
            hosts=host_list,
            gather_facts=self.gather_facts,
            tasks=[dict(action=dict(module=module_name, args=module_args))])
        play = Play().load(play_source,
                           loader=self.loader,
                           variable_manager=self.variable_manager)
        tqm = None
        try:
            tqm = TaskQueueManager(inventory=self.inventory,
                                   variable_manager=self.variable_manager,
                                   loader=self.loader,
                                   options=self.options,
                                   passwords=self.passwords,
                                   stdout_callback=self.callback)
            tqm._stdout_callback = self.callback
            constants.HOST_KEY_CHECKING = False  # 关闭第一次使用ansible连接客户端是输入命令
            tqm.run(play)
        except Exception as err:
            logger.error(msg=err)
        finally:
            if tqm is not None:
                tqm.cleanup()
            if self.loader:
                self.loader.cleanup_all_tmp_files()
示例#22
0
def run(host, user, passwd, tasks):
    Options = namedtuple('Options', [
        'connection', 'module_path', 'forks', 'remote_user',
        'private_key_file', 'ssh_common_args', 'ssh_extra_args',
        'sftp_extra_args', 'scp_extra_args', 'become', 'become_method',
        'become_user', 'verbosity', 'check'
    ])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='smart',
                      module_path='none',
                      forks=100,
                      remote_user=user,
                      private_key_file=None,
                      ssh_common_args=None,
                      ssh_extra_args=None,
                      sftp_extra_args=None,
                      scp_extra_args=None,
                      become=True,
                      become_method="sudo",
                      become_user="******",
                      verbosity=None,
                      check=False)
    passwords = {'conn_pass': passwd, 'become_pass': ""}
    inventory = Inventory(loader=loader,
                          variable_manager=variable_manager,
                          host_list=host)
    variable_manager.set_inventory(inventory)
    host_list = []
    for h in host:
        host_list.append(h.split(":")[0])
    play_source = dict(name="Ansible Play",
                       hosts=host_list,
                       gather_facts='no',
                       tasks=tasks)
    print(play_source)
    play = Play().load(play_source,
                       variable_manager=variable_manager,
                       loader=loader)

    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
        )
        tqm._stdout_callback = callback
        tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
    return callback.host_ok.items(), callback.host_failed.items(
    ), callback.host_unreachable.items()
示例#23
0
def main():
    host_list = ['localhost', 'www.example.com', 'www.google.com']
    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'remote_user',
                                     'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
                                     'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='smart', module_path='/usr/share/ansible', forks=100,
                      remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
                      sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
                      become_user=None, verbosity=None, check=False)

    passwords = dict()

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source = dict(
        name="Ansible Play",
        hosts=host_list,
        gather_facts='no',
        tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
    )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # actually run it
    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
        )
        tqm._stdout_callback = callback
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()

    print("UP ***********")
    for host, result in callback.host_ok.items():
        print('{} >>> {}'.format(host, result._result['stdout']))

    print("FAILED *******")
    for host, result in callback.host_failed.items():
        print('{} >>> {}'.format(host, result._result['msg']))

    print("DOWN *********")
    for host, result in callback.host_unreachable.items():
        print('{} >>> {}'.format(host, result._result['msg']))
示例#24
0
    def run(self, host_list, module_name, module_args,):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        self.results_raw = {'success':{}, 'failed':{}, 'unreachable':{}}
        Options = namedtuple('Options', ['connection','module_path', 'forks', 'timeout',  'remote_user',
                'ask_pass', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
                'scp_extra_args', 'become', 'become_method', 'become_user', 'ask_value_pass', 'verbosity', 'check'])


        options = Options(connection='smart', module_path='/usr/share/ansible', forks=100, timeout=10,
                remote_user='******', ask_pass=False, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
                sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
                become_user='******',ask_value_pass=False, verbosity=None, check=False)

        passwords = dict(sshpass=None, becomepass=None)

        # create play with tasks
        play_source = dict(
                name="Ansible Play",
                hosts=host_list,
                gather_facts='no',
                tasks=[dict(action=dict(module=module_name, args=module_args))]
        )
        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)

        # actually run it
        tqm = None
        callback = ResultsCollector()
        try:
            tqm = TaskQueueManager(
                    inventory=self.inventory,
                    variable_manager=self.variable_manager,
                    loader=self.loader,
                    options=options,
                    passwords=passwords,
            )
            tqm._stdout_callback = callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()

        for host, result in callback.host_ok.items():
            self.results_raw['success'][host] = result._result.get('stdout') + result._result.get('stderr')

        for host, result in callback.host_failed.items():
            self.results_raw['failed'][host] = result._result.get('stdout') + result._result.get('stderr')

        for host, result in callback.host_unreachable.items():
            self.results_raw['unreachable'][host]= result._result['msg']

        logger.info(self.results_raw)
        return self.results_raw
示例#25
0
    def run(self, workname, host_list, module_name, module_args, work_uuid, username, callback='mongo', describe=''):

        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        play_source = dict(
            name=workname,
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))]
        )

        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
        try:
            self.host_list = self.inventory.list_hosts(host_list)
            print("self.host_list", self.host_list)
        except Exception as e:
            self.host_list = []
        if len(self.host_list) == 0:
            # self.logger.error(self.log_prefix + '准备工作失败,原因:没有匹配主机名')
            return False, '执行失败,没有匹配主机名'
        tqm = None
        # if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)
        # else:self.callback = ModelResultsCollector()
        # self.callback = ModelResultsCollector()
        if callback == 'mongo':
            self.callback = JsonCallback(work_uuid, workname, 'adhoc', self.options, describe, module_name=module_name,
                                           module_args=module_args, pattern=host_list, username=username)
        else:
            self.callback = ModelResultsCollector()
        import traceback
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback="minimal",
            )
            tqm._stdout_callback = self.callback
            C.HOST_KEY_CHECKING = False  # 关闭第一次使用ansible连接客户端是输入命令
            tqm.run(play)
            print("tqm.run")
        except Exception as err:
            print(traceback.print_exc())
            # DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err)
            # if self.logId:AnsibleSaveResult.Model.insert(self.logId, err)
        finally:
            if tqm is not None:
                tqm.cleanup()
示例#26
0
def run_playbook(inventory_filename, playbook_filename):
    '''
    Эта функция выполняет playbook и возвращает все результаты
    в виде словаря

    Параметры:
        * inventory_filename - имя инвентарного файла
        * playbook_filename - имя playbook
    '''
    variable_manager = VariableManager()
    loader = DataLoader()

    Options = namedtuple('Options',
                    ['connection', 'module_path', 'forks', 'become',
                     'become_method', 'become_user', 'check'])
    options = Options(connection='local', module_path='', forks=100,
        become=False, become_method='', become_user='', check=False)
    passwords = dict(vault_pass='******')

    inventory = Inventory(loader=loader, variable_manager=variable_manager,
                          host_list=inventory_filename)
    variable_manager.set_inventory(inventory)

    with open(playbook_filename) as f:
        playbook_content = yaml.load(f)

    return_result_dict = odict()
    for play_src in playbook_content:
        play = Play().load(play_src, variable_manager=variable_manager, loader=loader)

        tqm = None
        callback = CallbackModule()

        try:
            tqm = TaskQueueManager(
                    inventory=inventory,
                    variable_manager=variable_manager,
                    loader=loader,
                    options=options,
                    passwords=passwords,
                )
            tqm._stdout_callback = callback
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()

        return_result_dict[play_src['name']] = callback.results[0]
    return return_result_dict
def main(host_list,module,args):
    Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user',
            'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
            'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='smart', module_path='xxx', forks=50,
            remote_user='******', ssh_common_args=None, ssh_extra_args=None,
            sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
            become_user=None, verbosity=None, check=False)

    passwords = dict(sshpass=None, becomepass=None)

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source =  dict(
            name = "Ansible Play",
            hosts = host_list,
            gather_facts = 'no',
            tasks = [ dict(action=dict(module=module, args=args)) ]
        )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # actually run it
    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
                inventory=inventory,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords,
            )
        tqm._stdout_callback = callback
        tqm.run(play)
        return callback.results[0]['tasks'][0]['hosts']

    finally:
        if tqm is not None:
            tqm.cleanup()
示例#28
0
def autocreate_publickey(host_list, password, jobid):
    C.HOST_KEY_CHECKING = False
    loader = DataLoader()
    options = Options(connection='smart',
                      forks=5,
                      ssh_common_args='-C -o ControlPersist=30s')
    passwords = dict()
    if len(host_list) <= 1:
        sources = host_list[0] + ','
    else:
        sources = ','.join(host_list)
    inventory = InventoryManager(loader=loader, sources=sources)
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    for host in host_list:
        host_info = Host(name=host, port=22)
        variable_manager.set_host_variable(host_info, 'ansible_ssh_user',
                                           'root')
        variable_manager.set_host_variable(host_info, 'ansible_ssh_pass',
                                           password)
    play_source = dict(
        name='Generate Publickey',
        hosts=host_list,
        gather_facts='no',
        tasks=[
            dict(action=dict(
                module='authorized_key',
                args=dict(user='******',
                          key="{{ lookup('file','/root/.ssh/id_rsa.pub') }}")))
        ])
    play = Play().load(play_source,
                       variable_manager=variable_manager,
                       loader=loader)
    tqm = None
    callback = ResultsCollector(jobid)
    try:
        tqm = TaskQueueManager(inventory=inventory,
                               variable_manager=variable_manager,
                               loader=loader,
                               options=options,
                               passwords=passwords)
        tqm._stdout_callback = callback
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
    return callback.result
示例#29
0
    def run(self):
        self.variable_manager.set_inventory(self.inventory)
        play = Play().load(self.create_play_tasks(),
                           variable_manager=self.variable_manager, loader=self.loader)
        tqm = None
        callback = ResultsCollector()

        tqm = TaskQueueManager(
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=self.passwords
        )
        tqm._stdout_callback = callback
        result = tqm.run(play)

        return result, callback
示例#30
0
def run_ntcshow(username, password, hostname, cmd, driver):
    inventory = set_inventory(hostname)
    play_source = dict(
        name='BICS  API',
        hosts=hostname,
        gather_facts='False',
        tasks=[
            dict(action=dict(
                module='ntc_show_command',
                args=dict(
                    connection='netmiko_ssh',
                    platform=driver,
                    command=cmd,
                    template_dir=
                    '/home/beta/ntc-ansible/ntc-templates/templates',
                    host=hostname,
                    username=username,
                    password=password,
                    secret=password,
                )))
        ])

    play = Play().load(play_source,
                       variable_manager=variable_manager,
                       loader=loader)
    tqm = None
    callback = ResultsCollector()

    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=None,
            run_tree=False,
        )
        tqm._stdout_callback = callback
        result = tqm.run(play)
        return callback

    finally:
        if tqm is not None:
            tqm.cleanup()
示例#31
0
 def run(self):
     # actually run it
     tqm = None
     try:
         tqm = TaskQueueManager(
             inventory=self.inventory,
             variable_manager=self.variable_manager,
             loader=self.loader,
             options=self.options,
             passwords=dict(),
         )
         tqm._stdout_callback = self.call_back
         result = tqm.run(self.play)
         self._summary = self.call_back.summary
         self._results = self.call_back.results
         return result
     finally:
         if tqm is not None:
             tqm.cleanup()
示例#32
0
文件: o.py 项目: haroldTlan/ansible
def run_adhoc(ip, order):
    variable_manager.extra_vars = {
        "ansible_ssh_user": "******",
        "ansible_ssh_pass": "******"
    }
    play_source = {
        "name": "Ansible Ad-Hoc",
        "hosts": "%s" % ip,
        "gather_facts": "no",
        "tasks": [{
            "action": {
                "module": "command",
                "args": "%s" % order
            }
        }]
    }
    #    play_source = {"name":"Ansible Ad-Hoc","hosts":"192.168.2.160","gather_facts":"no","tasks":[{"action":{"module":"command","args":"python ~/store.py del"}}]}
    play = Play().load(play_source,
                       variable_manager=variable_manager,
                       loader=loader)
    tqm = None
    callback = ResultsCollector()

    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=None,
            #stdout_callback='minimal',
            #stdout_callback=results_callback,
            run_tree=False,
        )
        tqm._stdout_callback = callback
        result = tqm.run(play)
        return callback

    finally:
        if tqm is not None:
            tqm.cleanup()
示例#33
0
    def run_ad_hoc(self, host, module_name, module_args):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """

        self.callback = AdHocResultCallback(self.uuid, self.sock)

        # create play with tasks
        play_source = dict(
            name="Ansible ad-hoc",
            hosts=host,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))])

        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)

        # actually run it
        tqm = None
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            tqm._stdout_callback = self.callback
            C.HOST_KEY_CHECKING = False
            tqm.run(play)
        except Exception as e:
            Task.objects.filter(id=self.task_id).update(error_msg=str(e),
                                                        executed=True)
        finally:
            if tqm is not None:
                tqm.cleanup()
            shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
示例#34
0
    def run_play(self, host_list, module_name, module_args):
        """
        run play
        :param host_list is list,
        :param module_name is string
        :param module_args is string
        """
        play = None
        # create play with tasks
        play_source = dict(
            name="Ansible Play",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))])
        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)
        # actually run it
        tqm = None
        display = LogDisplay(logname=self.job_id)
        callback = CALLBACKMODULE[CALLBACK](display=display)
        if module_name == 'backup':
            # 对于备份模块,特殊处理,必须使用minimal,才能获取到文件名属性
            callback = minimal_callback(display=display)

        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            tqm._stdout_callback = callback
            tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()

        return display.get_log_json()
示例#35
0
    def run_play(self, host_list, module_name, module_args):
        """
        run play
        :param host_list is list,
        :param module_name is string
        :param module_args is string
        """
        play = None
        # create play with tasks
        play_source = dict(
            name="Ansible Play",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))]
        )
        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
        # actually run it
        tqm = None
        display = LogDisplay(logname=self.job_id)
        callback = CALLBACKMODULE[CALLBACK](display=display)
        if module_name == 'backup':
            # 对于备份模块,特殊处理,必须使用minimal,才能获取到文件名属性
            callback = minimal_callback(display=display)

        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
            )
            tqm._stdout_callback = callback
            tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()

        return display.get_log_json()
示例#36
0
    def run_model(self, host_list, module_name, module_args):
        """
        run module from andible ad-hoc.
        module_name: ansible module_name
        module_args: ansible module args
        """
        print(host_list)
        play_source = dict(
            name="Ansible Play",
            hosts=host_list,
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=module_args))])

        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)
        tqm = None
        # if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId)
        # else:self.callback = ModelResultsCollector()
        self.callback = ModelResultsCollector()
        import traceback
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback="minimal",
            )
            tqm._stdout_callback = self.callback
            tqm.run(play)
        except Exception as err:
            print(traceback.print_exc())
            # DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err)
            # if self.logId:AnsibleSaveResult.Model.insert(self.logId, err)
        finally:
            if tqm is not None:
                tqm.cleanup()