IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发工具 -> python 调用 ansible api -> 正文阅读

[开发工具]python 调用 ansible api

python 调用 ansible api


1.安装

   pip install ansible

注意:ansible 只能Linux运行
可以尝试pycharm 远程调试

2.调用方式

1.adhoc 直接调用ansible模块


# 指定 ansible 安装的modules
MODULE_PATH = "//home//production//env//devops//lib//python3.7//site-packages//ansible//modules"

def adhoc(host_list, task_list, remote_user='root', become=None, become_user=None):
    # since the API is constructed for CLI it expects certain options to always be set in the context object
    context.CLIARGS = ImmutableDict(connection='smart', remote_user=remote_user, verbosity=3, module_path=MODULE_PATH,
                                    forks=20, become=become,
                                    become_method=None, become_user=become_user, check=False, diff=False)
    # required for
    # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    sources = ','.join(host_list)
    if len(host_list) == 1:
        sources += ','

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

    # Instantiate our ResultsCollectorJSONCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
    results_callback = ResultsCollectorJSONCallback()

    # create inventory, use path to host config file as source or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources=sources)

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

    # instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
    # IMPORTANT: This also adds library dirs paths to the module loader
    # IMPORTANT: and so it must be initialized before calling `Play.load()`.
    tqm = TaskQueueManager(
        inventory=inventory,
        variable_manager=variable_manager,
        loader=loader,
        passwords=passwords,
        stdout_callback=results_callback,
        # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
    )

    # 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=host_list,
        gather_facts='no',
        tasks=task_list
    )

    # 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 = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # Actually run it
    try:
        result = tqm.run(play)  # most interesting data for a play is actually sent to the callback's methods
    except Exception as e:
        return e
    finally:
        # we always need to cleanup child procs and the structures we use to communicate with them
        tqm.cleanup()
        if loader:
            loader.cleanup_all_tmp_files()

    # Remove ansible tmpdir
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    def get_result():
        results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
        for _hosts, result in results_callback.host_ok.items():
            results_raw['success'][_hosts] = result._result
        for _hosts, result in results_callback.host_failed.items():
            results_raw['failed'][_hosts] = result._result
        for _hosts, result in results_callback.host_unreachable.items():
            results_raw['unreachable'][_hosts] = result._result

        return results_raw

    _get_result = get_result()
    return _get_result

2.playbook 调用yaml脚本

def execPlaybook(playbooks,host_list, remote_user='production', become=None, become_user=None):
    context.CLIARGS = ImmutableDict(connection='smart', remote_user=remote_user, verbosity=3, module_path=MODULE_PATH,
                                    forks=20, become=become, syntax=None, start_at_task=None,
                                    become_method=None, become_user=become_user, check=False, diff=False)

    sources = ','.join(host_list)
    if len(host_list) == 1:
        sources += ','

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

    # Instantiate our ResultsCollectorJSONCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
    results_callback = ResultsCollectorJSONCallback()

    # create inventory, use path to host config file as source or hosts in a comma separated string
    inventory = InventoryManager(loader=loader, sources=sources)

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


    playbook = PlaybookExecutor(playbooks=playbooks,
                                inventory=inventory,
                                variable_manager=variable_manager,
                                loader=loader,
                                passwords=passwords)

    # 使用回调函数
    playbook._tqm._stdout_callback = results_callback
    try:
        result = playbook.run()
    except Exception as e:
        return e

    # Remove ansible tmpdir
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    def get_result():
        results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
        for _hosts, result in results_callback.host_ok.items():
            results_raw['success'][_hosts] = result._result
        for _hosts, result in results_callback.host_failed.items():
            results_raw['failed'][_hosts] = result._result
        for _hosts, result in results_callback.host_unreachable.items():
            results_raw['unreachable'][_hosts] = result._result

        return results_raw

    _get_result = get_result()
    return _get_result

3.设置回调方法

class ResultsCollectorJSONCallback(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 __init__(self, *args, **kwargs):
        super(ResultsCollectorJSONCallback, self).__init__(*args, **kwargs)
        self.host_ok = {}
        self.host_unreachable = {}
        self.host_failed = {}

    def v2_runner_on_unreachable(self, result):
        host = result._host
        self.host_unreachable[result._host.get_name()] = {
            "unreachable": result._result.get("unreachable"),
            "msg": result._result.get("msg")}

    def v2_runner_on_ok(self, result, *args, **kwargs):
        """Print a json representation of the result.

        Also, store the result in an instance attribute for retrieval later
        """
        self.host_ok[result._host.get_name()] = {
            "stdout_lines": result._result.get("stdout_lines"),
            "stderr_lines": result._result.get("stderr_lines"),
            "cmd": result._result.get("cmd"),
            "delta": result._result.get("delta"),
            "start": result._result.get("start"),
            'end': result._result.get("end"),
            "rc": result._result.get("rc"),
            "changed": result._result.get("changed")}

    def v2_runner_on_failed(self, result, *args, **kwargs):
        self.host_failed[result._host.get_name()] = {
            "stdout_lines": result._result.get("stdout_lines"),
            "stderr_lines": result._result.get("stderr_lines"),
            "cmd": result._result.get("cmd"),
            "delta": result._result.get("delta"),
            "start": result._result.get("start"),
            "msg": result._result.get("msg"),
            'end': result._result.get("end"),
            "rc": result._result.get("rc"),
            "changed": result._result.get("changed")
        }

4.main方法使用

if __name__ == '__main__':
    # 指定主机,需要配置ssh
    host=['10.0.0.0','10.0.0.0']
    tasks=[
        # dict(name='222222',action=dict(module="setup")),
        dict(name='222222',action=dict(module="setup",args=dict(filter='ansible_nodename'))),
    result = adhoc(host_list=host,task_list=tasks)
    # result = execPlaybook(playbooks=['test1.yml'],host_list=host)
    print(json.dumps(result, indent=4))
  开发工具 最新文章
Postman接口测试之Mock快速入门
ASCII码空格替换查表_最全ASCII码对照表0-2
如何使用 ssh 建立 socks 代理
Typora配合PicGo阿里云图床配置
SoapUI、Jmeter、Postman三种接口测试工具的
github用相对路径显示图片_GitHub 中 readm
Windows编译g2o及其g2o viewer
解决jupyter notebook无法连接/ jupyter连接
Git恢复到之前版本
VScode常用快捷键
上一篇文章      下一篇文章      查看所有文章
加:2021-07-14 23:09:10  更:2021-07-14 23:09:12 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/20 13:31:50-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码