1. 程式人生 > >Ansible API 2.0解析

Ansible API 2.0解析

ansible

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


本文出自 “隔壁老張” 博客,請務必保留此出處http://xxuer.blog.51cto.com/11947593/1924235

Ansible API 2.0解析