importjsonfromcollectionsimportnamedtuplefromansible.parsing.dataloaderimportDataLoaderfromansible.varsimportVariableManagerfromansible.inventoryimportInventoryfromansible.playbook.playimportPlayfromansible.executor.task_queue_managerimportTaskQueueManagerfromansible.plugins.callbackimportCallbackBase


引用各个模块功能:

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):

#thehostfilefile,orscriptpath,orlistofhosts#ifalist,inventorydatawillNOTbeloaded#cachingtoavoidrepeatedcalculations,particularlywith


6、playbook.play

Ansible验证执行参数


源码中介绍

"""Aplayisalanguagefeaturethatrepresentsalistofrolesand/ortask/handlerblockstoexecuteonagivensetofhosts.Usage:Play.load(datastructure)->PlayPlay.something(...)"""


7、TaskQueueManager

Ansible多任务调度类

'''ThisclasshandlesthemultiprocessingrequirementsofAnsiblebycreatingapoolofworkerforks,aresulthandlerfork,andamanagerobjectwithshareddatastructures/queuesforcoordinatingworkbetweenallprocesses.Thequeuemanagerisresponsibleforloadingtheplaystrategyplugin,whichdispatchesthePlay'staskstohosts.''''''Iteratesovertheroles/tasksinaplay,usingthegiven(ordefault)strategyforqueueingtasks.Thedefaultisthelinearstrategy,whichoperateslikeclassicAnsiblebykeepingallhostsinlock-stepwithagiventask(meaningnohostsmoveontothenexttaskuntilallhostsaredonewiththecurrenttask).'''


8、CallbackBase

Ansible callback回调类


源码介绍

'''Thisisabaseansiblecallbackclassthatdoesnothing.Newcallbacksshouldusethisclassasabaseandoverrideanycallbackmethodstheywishtoexecutecustomactions.'''




接着看官方给的例子:

classResultCallback(CallbackBase):"""AsamplecallbackpluginusedforperforminganactionasresultscomeinIfyouwanttocollectallresultsintoasingleobjectforprocessingattheendoftheexecution,lookintoutilizingthe``json``callbackpluginorwritingyourowncustomcallbackplugin"""defv2_runner_on_ok(self,result,**kwargs):"""PrintajsonrepresentationoftheresultThismethodcouldstoretheresultinaninstanceattributeforretrievallater"""host=result._hostprintjson.dumps({host.name:result._result},indent=4)


可以看到上述就是一个回调类,用于自定义输出内容




接着看:

Options=namedtuple('Options',['connection','module_path','forks','become','become_method','become_user','check'])#initializeneededobjectsvariable_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')#InstantiateourResultCallbackforhandlingresultsastheycomeinresults_callback=ResultCallback()#createinventoryandpasstovarmanagerinventory=Inventory(loader=loader,variable_manager=variable_manager,host_list='localhost')variable_manager.set_inventory(inventory)#createplaywithtasksplay_source=dict(name="AnsiblePlay",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)

#initializeneededobjectsvariable_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')


初始化上面自定义的回调函数:

#InstantiateourResultCallbackforhandlingresultsastheycomeinresults_callback=ResultCallback()


创建inventory、并带进去参数

#createinventoryandpasstovarmanagerinventory=Inventory(loader=loader,variable_manager=variable_manager,host_list='localhost')variable_manager.set_inventory(inventory)


创建要执行play的内容并引入上面的:

#createplaywithtasksplay_source=dict(name="AnsiblePlay",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)


加入到任务队列并执行:

#actuallyrunittqm=Nonetry:tqm=TaskQueueManager(inventory=inventory,variable_manager=variable_manager,loader=loader,options=options,passwords=passwords,stdout_callback=results_callback,#Useourcustomcallbackinsteadofthe``default``callbackplugin)result=tqm.run(play)finally:iftqmisnotNone:tqm.cleanup()