Ansible API 2.0解析
admin
2023-07-30 06:00:15
0
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()


相关内容

热门资讯

烟花厂防爆挡墙竟是空心的!谁在... 防护屏障,俗称防爆挡墙,是烟花爆竹厂的相关区域出现危险状况的时候,用来减轻冲击波等因素对其他区域造成...
国家一级文物上现TCL广告字样... 近日,有网友称其在中国工艺美术馆举办的艺术展上发现,国家一级文物永乐款鎏金铜观音菩萨像展柜内,从特定...
胡锡进谈“人大通报蒋方舟被指论... 老胡仔细阅读了人民大学通报,简单翻译通报的内容就是:蒋方舟的硕士学位论文存在学术不规范问题,但不构成...
人民大学:蒋方舟硕士论文注释及... 情况通报针对举报反映我校文学院2019届硕士毕业生蒋某某硕士学位论文涉嫌学术不端一事,学校高度重视,...
伊拉克女信众:伊玛目哈梅内伊不... 哈梅内伊的公众告别悼念仪式,不仅有伊朗大批民众从各地赶来参加,由于哈梅内伊也是什叶派高级宗教人士,还...
央视曝光:线上公然售卖“遥控作... 早在2024年,《财经调查》曾报道过的农贸市场改装、使用“违规秤”的乱象,通过作弊芯片的算法,篡改了...
美的p7是什么故障代码 美的 P7 故障代码通常表示空调室外机排气温度过高保护。这可能是由于以下原因导致的:1. 室外机散热...
美的空调p7是什么故障 美的空调显示“P7”可能表示室外排气温度过高保护。当空调出现 P7 故障代码时,可能有以下原因:1....
空调出现P7什么意思 其主要原因有,1、室外排气高温保护。2、室外排气温度过高。3、机型选择错误。4、制冷剂量不足,制冷剂...
美的空调显示p7是什么意思 美的空调显示“P7”通常表示室外机排气温度过高保护。导致美的空调显示“P7”的原因可能有以下几种:1...