ansible的api

ansible2.0之前的api調用是很簡單的,2.0之後變得更靈活,也更復雜
 
[root@localhost ~]# cat ansibleapi.py
#!/usr/bin/env python
#coding:utf8

import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase

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))           #用json返回結果,四個縮進位

Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
# initialize needed objects
loader = DataLoader()
options = Options(connection='ssh',
                  module_path='/path/to/mymodules',
                  forks=100,
                  become=None,
                  become_method=None,
                  become_user=None,
                  check=False,
                  diff=False
)                        #connection爲鏈接方式
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 = InventoryManager(loader=loader, sources=['test.txt'])            #source爲inventory
variable_manager = VariableManager(loader=loader, inventory=inventory)

# create play with tasks
play_source =  dict(
        name = "Ansible Play",
        hosts = 'all',                        #分組
        gather_facts = 'no',
        tasks = [
            dict(action=dict(module='shell', args='ls'), register='shell_out'),         #調用的模塊和參數
            dict(action=dict(module='info', 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()


[root@localhost ~]# python ansibleapi.py
{
    "192.168.123.107": {
        "_ansible_parsed": true,
        "stderr_lines": [],
        "changed": true,
        "end": "2018-02-12 15:57:20.638437",
        "_ansible_no_log": false,
        "stdout": "anaconda-ks.cfg",
        "cmd": "ls",
        "start": "2018-02-12 15:57:20.634033",
        "delta": "0:00:00.004404",
        "stderr": "",
        "rc": 0,
        "invocation": {
            "module_args": {
                "creates": null,
                "executable": null,
                "_uses_shell": true,
                "_raw_params": "ls",
                "removes": null,
                "warn": true,
                "chdir": null,
                "stdin": null
            }
        },
        "stdout_lines": [
            "anaconda-ks.cfg"             //192.168.123.107的/root下只有一個文件
        ]
    }
}
相關文章
相關標籤/搜索