import json from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars import VariableManager from ansible.inventory import Inventory from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.plugins.callback import CallbackBase
引用各个模块功能:
1、Json模块忽略
2、namedtuple
见:http://xxuer.blog.51cto.com/11947593/1924122
3、DataLoader
用来加载解析yaml文件和JSON内容,并支持vault解密
源码中是这样介绍的:
The DataLoader class is used to load and parse YAML or JSON content, either from a given file name or from a string that was previously read in through other means. A Vault password can be specified, and any vault-encrypted files will be decrypted. Data read from files will also be cached, so the file will never be read from disk more than once. Usage: dl = DataLoader() # optionally: dl.set_vault_password(‘foo‘) ds = dl.load(‘...‘) ds = dl.load_from_file(‘/path/to/file‘) ‘‘‘ |
4、VariableManager
用来管理变量,包括主机、组、扩展等变量,该类在之前的Inventory内置
源码中是这样介绍的:
data = dict( fact_cache = self._fact_cache, np_fact_cache = self._nonpersistent_fact_cache, vars_cache = self._vars_cache, extra_vars = self._extra_vars, host_vars_files = self._host_vars_files, group_vars_files = self._group_vars_files, omit_token = self._omit_token, options_vars = self._options_vars, #inventory = self._inventory, )
5、Inventory
Ansible的用户管理组件
源码中介绍:
def __init__(self, loader, variable_manager, host_list=C.DEFAULT_HOST_LIST): |
# the host file file, or script path, or list of hosts # if a list, inventory data will NOT be loaded # caching to avoid repeated calculations, particularly with
6、playbook.play
Ansible验证执行参数
源码中介绍
""" A play is a language feature that represents a list of roles and/or task/handler blocks to execute on a given set of hosts. Usage: Play.load(datastructure) -> Play Play.something(...) """
7、TaskQueueManager
Ansible多任务调度类
‘‘‘ This class handles the multiprocessing requirements of Ansible by creating a pool of worker forks, a result handler fork, and a manager object with shared datastructures/queues for coordinating work between all processes. The queue manager is responsible for loading the play strategy plugin, which dispatches the Play‘s tasks to hosts. ‘‘‘ ‘‘‘ Iterates over the roles/tasks in a play, using the given (or default) strategy for queueing tasks. The default is the linear strategy, which operates like classic Ansible by keeping all hosts in lock-step with a given task (meaning no hosts move on to the next task until all hosts are done with the current task). ‘‘‘
8、CallbackBase
Ansible callback回调类
源码介绍
‘‘‘ This is a base ansible callback class that does nothing. New callbacks should use this class as a base and override any callback methods they wish to execute custom actions. ‘‘‘
接着看官方给的例子:
class ResultCallback(CallbackBase): """A sample callback plugin used for performing an action as results come in If you want to collect all results into a single object for processing at the end of the execution, look into utilizing the ``json`` callback plugin or writing your own custom callback plugin """ def v2_runner_on_ok(self, result, **kwargs): """Print a json representation of the result This method could store the result in an instance attribute for retrieval later """ host = result._host print json.dumps({host.name: result._result}, indent=4)
可以看到上述就是一个回调类,用于自定义输出内容
接着看:
Options = namedtuple(‘Options‘, [‘connection‘, ‘module_path‘, ‘forks‘, ‘become‘, ‘become_method‘, ‘become_user‘, ‘check‘]) # initialize needed objects variable_manager = VariableManager() loader = DataLoader() options = Options(connection=‘local‘, module_path=‘/path/to/mymodules‘, forks=100, become=None, become_method=None, become_user=None, check=False) passwords = dict(vault_pass=‘secret‘) # Instantiate our ResultCallback for handling results as they come in results_callback = ResultCallback() # create inventory and pass to var manager inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=‘localhost‘) variable_manager.set_inventory(inventory) # create play with tasks play_source = dict( name = "Ansible Play", hosts = ‘localhost‘, 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}}‘))) ] ) play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
定义选项的namedtuple(connection/become .....):
Options = namedtuple(‘Options‘, [‘connection‘, ‘module_path‘, ‘forks‘, ‘become‘, ‘become_method‘, ‘become_user‘, ‘check‘])
初始化下面三个对象(VariableManager、DataLoader、Namedtuple)
# initialize needed objects variable_manager = VariableManager() loader = DataLoader() options = Options(connection=‘local‘, module_path=‘/path/to/mymodules‘, forks=100, become=None, become_method=None, become_user=None, check=False) passwords = dict(vault_pass=‘secret‘)
初始化上面自定义的回调函数:
# Instantiate our ResultCallback for handling results as they come in results_callback = ResultCallback()
创建inventory、并带进去参数
# create inventory and pass to var manager inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=‘localhost‘) variable_manager.set_inventory(inventory)
创建要执行play的内容并引入上面的:
# create play with tasks play_source = dict( name = "Ansible Play", hosts = ‘localhost‘, 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}}‘))) ] ) play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
加入到任务队列并执行:
# actually run it tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords, stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup()
时间: 2024-10-28 20:12:25