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


相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...