首页 > 编程语言 >ansible python API

ansible python API

时间:2024-04-11 13:55:38浏览次数:30  
标签:API python loader callback host ansible result import

version: v2.9
官方示例如下:

点击查看代码
#!/usr/bin/env python

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import json
import shutil

import ansible.constants as C
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.module_utils.common.collections import ImmutableDict
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.plugins.callback import CallbackBase
from ansible.vars.manager import VariableManager
from ansible import context


# Create a callback plugin so we can capture the output
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[host.get_name()] = result

    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
        """
        host = result._host
        self.host_ok[host.get_name()] = result
        print(json.dumps({host.name: result._result}, indent=4))

    def v2_runner_on_failed(self, result, *args, **kwargs):
        host = result._host
        self.host_failed[host.get_name()] = result


def main():
    host_list = ['localhost', 'www.example.com', 'www.google.com']
    # since the API is constructed for CLI it expects certain options to always be set in the context object
    context.CLIARGS = ImmutableDict(connection='smart', module_path=['/to/mymodules', '/usr/share/ansible'], forks=10, become=None,
                                    become_method=None, become_user=None, 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(vault_pass='secret')

    # 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=[
            dict(action=dict(module='shell', args='ls'), register='shell_out'),
            dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}'))),
            dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime'))),
        ]
    )

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

    print("UP ***********")
    for host, result in results_callback.host_ok.items():
        print('{0} >>> {1}'.format(host, result._result['stdout']))

    print("FAILED *******")
    for host, result in results_callback.host_failed.items():
        print('{0} >>> {1}'.format(host, result._result['msg']))

    print("DOWN *********")
    for host, result in results_callback.host_unreachable.items():
        print('{0} >>> {1}'.format(host, result._result['msg']))


if __name__ == '__main__':
    main()

运行之后直接报错:Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

解决方法:把 passwords = dict(vault_pass='secret') 修改为: passwords = dict(conn_pass='secret'),参数名称修改过了,官网未更新。

标签:API,python,loader,callback,host,ansible,result,import
From: https://www.cnblogs.com/chenhuxy/p/18128968

相关文章

  • 文献学习-33-一个用于生成手术视频摘要的python库
    VideoSum:APythonLibraryforSurgicalVideoSummarizationAuthors: LuisC.Garcia-Peraza-Herrera,SebastienOurselin,andTomVercauterenSource: https://arxiv.org/pdf/2303.10173.pdf这篇文章主要关注的是如何通过视频摘要来简化和可视化手术视频,以便于数......
  • 批量压缩文件夹里的图片(python)
    起源是我收藏了很多照片,但是太大的照片不利于分享使用,而且我并不需要那么高清晰度,通过在线压缩工具tinypng又太慢拥有python下载python教程有很多,但我推荐使用anaconda管理python,可以灵活的管理python版本,还不会导致本地版本冲突压缩脚本安装pillow库,我在pycharm里可以直接......
  • Python基础语法
    1.常用数据类型2.注释单行注释#需要注释的内容多行注释"""需要注释的内容"""3.变量定义变量名=变量值type()查看数据类型type(需查看类型的数据)4.类型转换类型转换代码int(x)#将x转换成整型float(x)#将x转换成浮点型str(x)#将x转换成字......
  • 【python】python根据传入参数不同,调用不同的方法
    大家好,我是木头左。今天介绍三种不同方法实现根据传入参数不同,调用不同的方法。使用条件语句在Python中,可以使用条件语句(如if-elif-else语句)来根据传入的参数调用不同的方法。以下是一个示例:defmethod1():print("调用方法1")defmethod2():print("调用方法2")d......
  • 【华为OD】2024年华为OD机试C卷真题集:最新的真题集题库 C/C++/Java/python/JavaScript
    【华为OD】2024年C卷真题集:最新的真题集题库C/C++/Java/python/JavaScript【华为OD】2024年C卷真题集:最新的真题集题库C/C++/Java/python/JavaScript-CSDN博客华为OD机试2024年C卷真题题集题库,有2种分数的题目列表,分别是100分的列表、200分的列表需要订阅请看链接:C卷100......
  • 【python基本用法】python的相对引用
    要使用__init__.py将mouse_move作为一个包,可以按照以下步骤操作:在包含mouse_move模块的目录中创建一个空的__init__.py文件。这将使Python将该目录视为一个包。在__init__.py文件中,导入mouse_move模块,并将其添加到包中。例如,可以使用以下代码:frommouse_moveimportmouse_mo......
  • 千万不要将centos中python 默认2.7的编译器改为3.x的,会出现File “ usr bin yum“, li
    千万不要将centos中python默认2.7的编译器改为3.x的,在使用yum时,会报各种错,1、File"/usr/bin/yum",line30  exceptKeyboardInterrupt,e:原因是yum按python3.6解析2.7的语法出错了修改/usr/bin/yum文件中的第一行为#!/usr/bin/python2.72、 File"/usr/libexec/url......
  • pycharm安装ansible模块
    在pycharm中通过pipinstallansible==2.9时遇到报错:error:can'tcopy'lib\ansible\module_utils\ansible_release.py':doesn'texistornotaregularfile解决方法:Downloadthelatestzipreleaseversionfromgithub(e.g.https://github.com/ansib......
  • Cisco APIC 6.0(5h) M - 应用策略基础设施控制器
    CiscoAPIC6.0(5h)M-应用策略基础设施控制器ApplicationPolicyInfrastructureController(APIC)请访问原文链接:CiscoAPIC6.0(5h)M-应用策略基础设施控制器,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org思科应用策略基础设施控制器(APIC)CiscoNX-OS......
  • Python面试50题!面试巩固必看!【转】
    题目001:在Python中如何实现单例模式。点评:单例模式是指让一个类只能创建出唯一的实例,这个题目在面试中出现的频率极高,因为它考察的不仅仅是单例模式,更是对Python语言到底掌握到何种程度,建议大家用装饰器和元类这两种方式来实现单例模式,因为这两种方式的通用性最强,而且也可以顺便......