Python ansible.executor.playbook_executor.PlaybookExecutor() Examples

The following are 13 code examples of ansible.executor.playbook_executor.PlaybookExecutor(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ansible.executor.playbook_executor , or try the search function .
Example #1
Source File: checkpython.py    From Practical-Network-Automation-Second-Edition with MIT License 7 votes vote down vote up
def ansible_part():
    playbook_path = "checktemplate.yml"
    inventory_path = "hosts"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    loader = DataLoader()
    options = Options(connection='local', module_path='', forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=False, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    inventory = InventoryManager(loader=loader, sources=['inventory'])
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    executor = PlaybookExecutor(  
                playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader,  
                options=options, passwords=passwords)  
    results = executor.run()  
    print results 
Example #2
Source File: runner.py    From chain with Apache License 2.0 6 votes vote down vote up
def run(self):
        executor = PlaybookExecutor(
            playbooks=[self.playbook_path],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=self.passwords
        )

        if executor._tqm:
            executor._tqm._stdout_callback = self.results_callback
        executor.run()
        executor._tqm.cleanup()
        try:
            results_callback = self.results_callback.output['plays'][0]['tasks'][1]['hosts']
            status = self.results_callback.output['stats']
            results = {"results_callback": results_callback, "status": status}
            return results
        except Exception as e:

            raise AnsibleError(
                'The hostname parameter or groups parameter in the BaseInventory \
                               does not match the hosts parameter in the yaml file.{}'.format(e)) 
Example #3
Source File: runner.py    From devops with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        executor = PlaybookExecutor(
            playbooks=[self.playbook_path],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=self.passwords
        )

        if executor._tqm:
            executor._tqm._stdout_callback = self.results_callback
        executor.run()
        executor._tqm.cleanup()
        try:
            results_callback = self.results_callback.output['plays'][0]['tasks'][1]['hosts']
            status = self.results_callback.output['stats']
            results = {"results_callback": results_callback, "status": status}
            return results
        except Exception as e:

            raise AnsibleError(
                'The hostname parameter or groups parameter in the BaseInventory \
                               does not match the hosts parameter in the yaml file.{}'.format(e)) 
Example #4
Source File: execute_playbook.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def execute_playbook():
    playbook_path = "playbook_template.yml"
    inventory_path = "hosts"

    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff', 'listhosts', 'listtasks', 'listtags', 'syntax'])
    loader = DataLoader()
    options = Options(connection='local', module_path='', forks=100, become=None, become_method=None, become_user=None, check=False,
                    diff=False, listhosts=False, listtasks=False, listtags=False, syntax=False)
    passwords = dict(vault_pass='secret')

    inventory = InventoryManager(loader=loader, sources=['inventory'])
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    executor = PlaybookExecutor(  
                playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader,  
                options=options, passwords=passwords)  
    results = executor.run()  
    print results 
Example #5
Source File: ansible_api.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def run_playbook(self, playbook_path,extra_vars=None):
        """
        run ansible palybook
        """
        try:
            # if self.redisKey:self.callback = PlayBookResultsCollectorToSave(self.redisKey,self.logId)
            self.callback = PlayBookResultsCollector()
            if extra_vars:self.variable_manager.extra_vars = extra_vars
            executor = PlaybookExecutor(
                playbooks=[playbook_path], inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader,
                options=self.options, passwords=self.passwords,
            )
            executor._tqm._stdout_callback = self.callback
            constants.HOST_KEY_CHECKING = False #关闭第一次使用ansible连接客户端是输入命令
            executor.run()
        except Exception as err:
            return False 
Example #6
Source File: runner.py    From autoops with Apache License 2.0 6 votes vote down vote up
def run(self):
            executor = PlaybookExecutor(
                playbooks=[self.playbook_path],
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords
            )

            if executor._tqm:
                executor._tqm._stdout_callback = self.results_callback
            executor.run()
            executor._tqm.cleanup()
            try:
                results_callback=self.results_callback.output['plays'][0]['tasks'][1]['hosts']
                status=self.results_callback.output['stats']
                results={"results_callback":results_callback,"status":status}
                return results
            except Exception as e:
                raise AnsibleError('The hostname parameter or groups parameter in the BaseInventory \
                                   does not match the hosts parameter in the yaml file.') 
Example #7
Source File: runner.py    From contrail-docker with Apache License 2.0 6 votes vote down vote up
def run(self, verbose=False):
        if not verbose:
            # Results of PlaybookExecutor
            cb = DisplayErrorCallback()
            self.pbex._tqm._stdout_callback = cb
        try:
            res = self.pbex.run()
        except AnsibleParserError as err:
            print(err)
            return None
        stats = self.pbex._tqm._stats

        # Test if success for record_logs
        run_success = True
        hosts = sorted(stats.processed.keys())
        for h in hosts:
            t = stats.summarize(h)
            if t['unreachable'] > 0 or t['failures'] > 0:
                run_success = False

        return stats 
Example #8
Source File: AnsibleApi_v29.py    From AnsibleUI with GNU General Public License v3.0 5 votes vote down vote up
def load_callbacks(self):   # 为callback 设置存储id
        pass

# 重新封装 PlaybookExecutor , 传入 task_id 
Example #9
Source File: runner.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def run(self, playbook_path, extra_vars=None, **kwargs):
        C.DEFAULT_ROLES_PATH = self.options.roles_path
        if extra_vars and isinstance(extra_vars, dict):
            self.variable_manager.extra_vars = extra_vars
        executor = PlaybookExecutor(
            playbooks=[playbook_path],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=self.options.passwords
        )

        if executor._tqm:
            executor._tqm._stdout_callback = self.results_callback

        try:
            executor.run()
            return self.results_callback.results
        except AnsibleError:
            executor._tqm.cleanup()
            self.loader.cleanup_all_tmp_files() 
Example #10
Source File: ansible_task.py    From heartbeats with MIT License 5 votes vote down vote up
def __init__(self, host_list, playbook_path, private_key_file="/root/.ssh/id_rsa", forks=5, extra_vars=None):
        super(AnsiblePlayTask, self).__init__(host_list, private_key_file, forks, extra_vars)
        passwords = {}
        self.call_back = result_collector.CallbackModule()
        self.pbex = PlaybookExecutor(playbooks=[playbook_path],
                                     inventory=self.inventory,
                                     variable_manager=self.variable_manager,
                                     loader=self.loader,
                                     options=self.options,
                                     passwords=passwords)
        self.pbex._tqm._stdout_callback = self.call_back 
Example #11
Source File: playbook.py    From ceph-ansible-copilot with GNU Lesser General Public License v2.1 5 votes vote down vote up
def setup(self, pb_file):

        self.pb_file = pb_file
        self.playbook = PlaybookExecutor(playbooks=[self.pb_file],
                                         inventory=self.inventory,
                                         variable_manager=self.variable_manager,
                                         loader=self.loader,
                                         options=self.options,
                                         passwords={}) 
Example #12
Source File: runner.py    From contrail-docker with Apache License 2.0 5 votes vote down vote up
def __init__(self, playbook, inventory, run_data=None, verbosity=0, tags=None, skip_tags=None):
        self.run_data = run_data or {}
        self.options = Options()

        self.options.verbosity = verbosity
        self.options.connection = 'local'  # Need a connection type "smart" or "ssh"
        self.options.become = True
        self.options.become_method = 'sudo'
        self.options.become_user = 'root'
        self.options.tags = tags or []
        self.options.skip_tags = skip_tags or []
        # Set global verbosity
        self.display = Display()
        self.display.verbosity = self.options.verbosity
        # Executor appears to have it's own
        # verbosity object/setting as well
        playbook_executor.verbosity = self.options.verbosity

        # Become Pass Needed if not logging in as user root
        passwords = {}

        # Gets data from YAML/JSON files
        self.loader = DataLoader()
        self.loader.set_vault_password(os.environ.get('VAULT_PASS',''))

        # All the variables from all the various places
        self.variable_manager = VariableManager()
        self.variable_manager.extra_vars = self.run_data

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

        # Setup playbook executor, but don't run until run() called
        self.pbex = playbook_executor.PlaybookExecutor(
            playbooks=[playbook],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=passwords) 
Example #13
Source File: ansible_utils.py    From bridgy with MIT License 4 votes vote down vote up
def __init__(self, playbook, hosts='hosts', options={}, passwords={}, vault_pass=None):

        # Set options
        self.options = Options()
        for k, v in options.iteritems():
            setattr(self.options, k, v)

        # Set global verbosity
        self.display = display
        self.display.verbosity = self.options.verbosity

        # Executor has its own verbosity setting
        playbook_executor.verbosity = self.options.verbosity

        # Gets data from YAML/JSON files
        self.loader = DataLoader()
        # Set vault password
        if vault_pass is not None:
            self.loader.set_vault_password(vault_pass)
        elif 'VAULT_PASS' in os.environ:
            self.loader.set_vault_password(os.environ['VAULT_PASS'])

        # All the variables from all the various places
        self.variable_manager = VariableManager()
        if self.options.python_interpreter is not None:
            self.variable_manager.extra_vars = {
                'ansible_python_interpreter': self.options.python_interpreter
            }

        # Set inventory, using most of above objects
        self.inventory = Inventory( loader=self.loader, 
                                    variable_manager=self.variable_manager,
                                    host_list=hosts)

        if len(self.inventory.list_hosts()) == 0:
            # Empty inventory
            self.display.error("Provided hosts list is empty.")
            sys.exit(1)

        self.inventory.subset(self.options.subset)

        if len(self.inventory.list_hosts()) == 0:
            # Invalid limit
            self.display.error("Specified limit does not match any hosts.")
            sys.exit(1)

        self.variable_manager.set_inventory(self.inventory)

        # Setup playbook executor, but don't run until run() called
        self.pbex = playbook_executor.PlaybookExecutor(
            playbooks=[playbook],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=passwords)