python 调用ansible 接口


获取组或者主机

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from collections import namedtuple
# 核心类
# 用于读取YAML和JSON格式的文件
from ansible.parsing.dataloader import DataLoader
# 用于存储各类变量信息
from ansible.vars.manager import VariableManager
# 用于导入资产文件
from ansible.inventory.manager import InventoryManager


# InventoryManager类的调用方式
def InventoryManagerStudy():
    dl = DataLoader()
    # loader= 表示是用什么方式来读取文件  sources=就是资产文件列表,里面可以是相对路径也可以是绝对路径
    im = InventoryManager(loader=dl, sources=["/etc/ansible/hosts"])

    # 获取指定资产文件中所有的组以及组里面的主机信息,返回的是字典,组名是键,主机列表是值
    allGroups = im.get_groups_dict()
    print(allGroups)

    # 获取指定组的主机列表
    print(im.get_groups_dict().get("web"))

    # 获取指定主机,这里返回的是host的实例
    host = im.get_host("192.168.28.108")
    print(host)
    # 获取该主机所有变量
    print(host.get_vars())
    # 获取该主机所属的组
    print(host.get_groups())


def main():
    InventoryManagerStudy()


if __name__ == "__main__":
    try:
        main()
    finally:
        sys.exit()

执行adhoc

样例1:远程执行域名解析

#!/usr/bin/env python

import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
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
from ansible import context
import ansible.constants as C


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
     一个示例回调插件,用于在返回结果时执行操作

     如果要将所有结果收集到单个对象中以便在执行结束时,请考虑使用“json”回调插件
     或者编写自己的自定义回调插件
    """

    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
        打印结果的json表示
        此方法可以将结果存储在实例属性中,以便以后检索
        """
        host = result._host
        print(json.dumps({host.name: result._result}, indent=4))


# since the API is constructed for CLI it expects certain options to always be set in the context object
context.CLIARGS = ImmutableDict(connection='local', module_path=['/to/mymodules'], forks=10, become=None,
                                become_method=None, become_user=None, check=False, diff=False)

# initialize needed objects
loader = DataLoader()  # Takes care of finding and reading yaml, json and ini files
passwords = dict(vault_pass='secret')

# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
# 实例化ResultCallback,以便在结果传入时处理它们。Ansible预计这将是其主要的展示渠道之一
results_callback = ResultCallback()

# create inventory, use path to host config file as source or hosts in a comma separated string
# 创建资源清册,将主机配置文件的路径用作逗号分隔字符串中的源或主机
inventory = InventoryManager(loader=loader, sources='/etc/ansible/hosts')

# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)

# create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.

play_source = dict(
    name="Ansible Play",
    hosts='192.168.28.108',
    gather_facts='no',
    tasks=[
        dict(action=dict(module='shell', args='nslookup www.baidu.com'), register='shell_out'),
        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
    ]
)

# Create play object, playbook objects use .load instead of init or new methods,
# this will also automatically create the task objects from the info provided in play_source
# 创建play对象,playbook对象使用.load而不是init或new方法,
# 这也会根据play_source中提供的信息自动创建任务对象
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

# Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
# 运行它-实例化任务队列管理器,它负责分叉和设置所有对象以迭代主机列表和任务
tqm = None
try:
    tqm = TaskQueueManager(
        inventory=inventory,
        variable_manager=variable_manager,
        loader=loader,
        passwords=passwords,
        stdout_callback=results_callback,
        # 使用我们的自定义回调,而不是打印到stdout的“default”回调插件
        # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
    )
    result = tqm.run(play)
    # 剧本中最有趣的数据实际上被发送到回调函数的方法
    # most interesting data for a play is actually sent to the callback's methods
finally:
    # we always need to cleanup child procs and the structures we use to communicate with them
    # 我们总是需要清理子进程以及用于与它们通信的结构
    if tqm is not None:
        tqm.cleanup()

    # Remove ansible tmpdir
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
{
    "192.168.28.108": {
        "changed": true,
        "end": "2020-07-09 06:07:19.535960",
        "stdout": "Server:\t\t192.168.28.249\nAddress:\t192.168.28.249#53\n\nNon-authoritative answer:\nwww.baidu.com\tcanonical name = www.a.shifen.com.\nName:\twww.a.shifen.com\nAddress: 14.215.177.38\nName:\twww.a.shifen.com\nAddress: 14.215.177.39",
        "cmd": "nslookup www.baidu.com",
        "rc": 0,
        "start": "2020-07-09 06:07:19.506950",
        "stderr": "",
        "delta": "0:00:00.029010",
        "invocation": {
            "module_args": {
                "creates": null,
                "executable": null,
                "_uses_shell": true,
                "strip_empty_ends": true,
                "_raw_params": "nslookup www.baidu.com",
                "removes": null,
                "argv": null,
                "warn": true,
                "chdir": null,
                "stdin_add_newline": true,
                "stdin": null
            }
        },
        "stdout_lines": [
            "Server:\t\t192.168.28.249",
            "Address:\t192.168.28.249#53",
            "",
            "Non-authoritative answer:",
            "www.baidu.com\tcanonical name = www.a.shifen.com.",
            "Name:\twww.a.shifen.com",
            "Address: 14.215.177.38",
            "Name:\twww.a.shifen.com",
            "Address: 14.215.177.39"
        ],
        "stderr_lines": [],
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        },
        "warnings": [
            "Platform darwin on host 192.168.28.108 is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information."
        ],
        "_ansible_no_log": false
    }
}
{
    "192.168.28.108": {
        "msg": "Server:\t\t192.168.28.249\nAddress:\t192.168.28.249#53\n\nNon-authoritative answer:\nwww.baidu.com\tcanonical name = www.a.shifen.com.\nName:\twww.a.shifen.com\nAddress: 14.215.177.38\nName:\twww.a.shifen.com\nAddress: 14.215.177.39",
        "_ansible_verbose_always": true,
        "_ansible_no_log": false,
        "changed": false
    }
}