• python学习之ansible api


    Python API 2.0

    从2.0的事情开始更复杂一些,但是你会得到更多离散和可读的类:

    #!/usr/bin/env python
    
    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
    
    class ResultCallback(CallbackBase):
        """用于执行结果的示例回调插件
    
         如果要将所有结果收集到单个对象进行处理
         执行的结束,看看利用``json``回调插件
         或编写自己的自定义回调插件
        """
        def v2_runner_on_ok(self, result, **kwargs):
            """打印结果的json表示
    
             该方法可以将结果存储在实例属性中以供以后检索
            """
            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')
    
    #实例化我们的ResultCallback来处理结果进来时
    results_callback = ResultCallback()
    
    #创建库存并传递给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)
    
    # 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()
    

    Python API pre 2.0

    这很简单:

    import ansible.runner
    
    runner = ansible.runner.Runner(
       module_name='ping',
       module_args='',
       pattern='web*',
       forks=10
    )
    datastructure = runner.run()
    

    运行方法返回每个主机的结果,根据是否可以联系来分组。 返回类型是模块特定的,如关于模块文档中所示:

    {
        "dark" : {
           "web1.example.com" : "failure message"
        },
        "contacted" : {
           "web2.example.com" : 1
        }
    }

    一个模块可以返回任何类型的JSON数据,所以Ansible可以作为框架来快速构建强大的应用程序和脚本。

    详细API示例

    以下脚本打印出所有主机的正常运行时间信息:

    #!/usr/bin/python
    
    import ansible.runner
    import sys
    
    # construct the ansible runner and execute on all hosts
    results = ansible.runner.Runner(
        pattern='*', forks=10,
        module_name='command', module_args='/usr/bin/uptime',
    ).run()
    
    if results is None:
       print "No hosts found"
       sys.exit(1)
    
    print "UP ***********"
    for (hostname, result) in results['contacted'].items():
        if not 'failed' in result:
            print "%s >>> %s" % (hostname, result['stdout'])
    
    print "FAILED *******"
    for (hostname, result) in results['contacted'].items():
        if 'failed' in result:
            print "%s >>> %s" % (hostname, result['msg'])
    
    print "DOWN *********"
    for (hostname, result) in results['dark'].items():
        print "%s >>> %s" % (hostname, result)
    

    高级程序员也可能希望将源读取到ansible本身,因为它使用API(具有所有可用选项)来实现可执行的命令行工具(lib / ansible / cli /)。

    更多信息请参考官网:http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html  

      

      

  • 相关阅读:
    VMware workstation 无法连接到虚拟机
    windows10彻底卸载sql server2017
    MySQL 8.0.19安装教程(windows 64位)
    IntelliJ IDEA 编译程序出现 非法字符 的 解决方法
    IDEA手动增加lib目录
    Idea Svn 导出代码
    intellij idea设置打开多个文件显示在多行tab上及设置 tab上打开文件的上限
    IDEA工作空间多开项目教程,多个项目放在一起
    SpringBoot+Shiro引起事务失效、错误原因、解决方法
    flex:1;的含义
  • 原文地址:https://www.cnblogs.com/leomei91/p/7255353.html
Copyright © 2020-2023  润新知