ansible python api 2.0使用

最近想利用python来调用anbile来实现一些功能,发现ansible的api已经升级到了2.0,使用上比以前复杂了许多。

这里我参考了官方文档的例子,做了一些整改,写了一个python调用ansible的函数,执行过程中输出执行结果。函数返回执行结果,便于筛选和存储所需的数据:

# vim exec_ansible.py
def exec_ansible(module,args,host):    
    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):
        def v2_runner_on_ok(self, result, **kwargs):
            host = result._host
            self.data = json.dumps({host.name: result._result}, indent=4)
            print(self.data)

    Options = namedtuple(‘Options‘, [‘connection‘, ‘module_path‘, ‘forks‘, ‘become‘, ‘become_method‘, ‘become_user‘, ‘check‘])
# initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    #module_path参数指定本地ansible模块包的路径
    options = Options(connection=‘smart‘, module_path=‘/usr/local/lib/python3.5/site-packages/ansible/modules/‘, forks=100, become=None, become_method=None, become_user=‘root‘, check=False)
    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
    #host_list指定本地ansible的hosts文件
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=‘/etc/ansible/hosts‘)
    variable_manager.set_inventory(inventory)

# create play with tasks
    play_source =  dict(
            name = "Ansible Play",
            #hosts可以指定inventory中的一组主机,也可指定单台主机
            hosts = host,
            gather_facts = ‘no‘,
            #task执行列表,如果想一次执行多个任务,可以在列表中添加任务
            tasks = [
                dict(action=dict(module=module, args=args), register=‘shell_out‘),
             ]
        )
    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,
              )
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup
        return json.loads(results_callback.data)

调用例子:

我本地ansible的hosts文件如下:

# more /etc/ansible/hosts
[testserver]
192.168.52.128
192.168.52.135

调用如下:

先调用testserver一组主机批量执行date命令:

>>> from exec_ansible import exec_ansible                             
>>> test1 = exec_ansible(module=‘shell‘,args=‘date‘,host=‘testserver‘)
{
    "192.168.52.135": {
        "warnings": [],
        "stderr": "",
        "delta": "0:00:00.003688",
        "_ansible_no_log": false,
        "stdout": "Sat Nov  5 18:54:17 CST 2016",
        "cmd": "date",
        "_ansible_parsed": true,
        "rc": 0,
        "invocation": {
            "module_args": {
                "removes": null,
                "executable": null,
                "creates": null,
                "chdir": null,
                "warn": true,
                "_raw_params": "date",
                "_uses_shell": true
            },
            "module_name": "command"
        },
        "start": "2016-11-05 18:54:17.563525",
        "changed": true,
        "end": "2016-11-05 18:54:17.567213",
        "stdout_lines": [
            "Sat Nov  5 18:54:17 CST 2016"
        ]
    }
}
{
    "192.168.52.128": {
        "warnings": [],
        "stderr": "",
        "delta": "0:00:00.003244",
        "_ansible_no_log": false,
        "stdout": "Sat Nov  5 21:48:38 CST 2016",
        "cmd": "date",
        "_ansible_parsed": true,
        "rc": 0,
        "invocation": {
            "module_args": {
                "removes": null,
                "executable": null,
                "creates": null,
                "chdir": null,
                "warn": true,
                "_raw_params": "date",
                "_uses_shell": true
            },
            "module_name": "command"
        },
        "start": "2016-11-05 21:48:38.252785",
        "changed": true,
        "end": "2016-11-05 21:48:38.256029",
        "stdout_lines": [
            "Sat Nov  5 21:48:38 CST 2016"
        ]
    }
}

指定单台执行命令:

>>> test2 = exec_ansible(module=‘shell‘,args=‘free -m‘,host=‘192.168.52.128‘)
{
    "192.168.52.128": {
        "warnings": [],
        "changed": true,
        "invocation": {
            "module_args": {
                "_raw_params": "free -m",
                "executable": null,
                "chdir": null,
                "creates": null,
                "removes": null,
                "_uses_shell": true,
                "warn": true
            },
            "module_name": "command"
        },
        "rc": 0,
        "start": "2016-11-05 21:53:10.738545",
        "_ansible_parsed": true,
        "delta": "0:00:00.002871",
        "stdout_lines": [
            "             total       used       free     shared    buffers     cached",
            "Mem:          1869       1786         83          3        312        512",
            "-/+ buffers/cache:        961        908 ",
            "Swap:         4047          3       4044 "
        ],
        "stderr": "",
        "end": "2016-11-05 21:53:10.741416",
        "cmd": "free -m",
        "_ansible_no_log": false,
        "stdout": "             total       used       free     shared    buffers     cached\nMem:          1869       1786         83          3        312        512\n-/+ buffers/cache:        961        908 \nSwap:         4047          3       4044 "
    }
}

这里可以从输出中取到输出结果:

>>> stdout = test2["192.168.52.128"]["stdout"]
             total       used       free     shared    buffers     cached
Mem:          1869       1756        112          2        314        490
-/+ buffers/cache:        951        917 
Swap:         4047          4       4043

我写的脚本有个bug,就是当指定一组主机批量执行的时候,返回的函数中,存储内容的只剩下最后执行命令的那台主机的相关信息,做不到把所有的主机的执行信息存储,希望有大神可以解决这个问题,并不吝赐教!!

时间: 2025-02-01 11:51:12

ansible python api 2.0使用的相关文章

Python API 2.0

Python API 2.0从2.0的事情开始更复杂一些,但是你会得到更多离散和可读的类: #!/usr/bin/env python import jsonfrom collections import namedtuplefrom ansible.parsing.dataloader import DataLoaderfrom ansible.vars import VariableManagerfrom ansible.inventory import Inventoryfrom ansi

自动化运维工具Ansible之Python API

Ansible 的Python API使用起来相当简单快捷,使用API可以将某些运维操作封装成一个带有WEB界面的操作,免去了每次执行某个操作的时候都需要SSH运行Ansible命令. 官方给出的一个简单示例: import ansible.runner          runner = ansible.runner.Runner(        module_name='ping',        module_args='',        pattern='web*',        f

Ansible playbook API 开发 调用测试

Ansible是Agentless的轻量级批量配置管理工具,由于出现的比较晚(13年)基于Ansible进行开发的相关文档较少,因此,这里通过一些小的实验,结合现有资料以及源码,探索一下Ansible的二次开发. 随笔的内容分为三个部分 playbook编辑执行 python 调用API执行playbook java调用python程序进行playbook的执行 实验的环境是centos6,ansible版本是1.9.4,python版本是2.6.6,jdk版本是1.7U79 一.playboo

Get skincluster data with maya’s python API

The code below demonstrates, via maya's python api, how to retrieve:– mObject from a mesh, and its skincluster– MFnSkinCluster for the skincluster on that mesh– the influences in that skin cluster and their names– the influence weights for every vert

Appium===Appium+Python API(转)

Appium+python自动化8-Appium Python API 前言: Appium Python API全集,不知道哪个大神整理的,这里贴出来分享给大家. 1.contexts contexts(self): Returns the contexts within the current session. 返回当前会话中的上下文,使用后可以识别H5页面的控件 :Usage: driver.contexts 用法 driver.contexts 2. current_context cu

Apache Qpid Python 1.35.0 发布

Apache Qpid Python 1.35.0 发布了,Apache Qpid (Open Source AMQP Messaging) 是一个跨平台的企业通讯解决方案,实现了高级消息队列协议.提供了 Java.C++ 两种服务端版本以及 Java.C++..NET.Python和Ruby语言的客户端. 增强: QPID-6475 - 08..09 Send connection.close before closing socket QPID-6567 - Support producer

Zabbix Python API 应用实战

做监控的同学应该知道,公司IDC机房经常有上架.下架.报修和报废的服务器.如果服务器数量很多的时候很容易造成监控遗漏.    大的互联网公司把监控系统和CMDB(资产管理系统|配置管理数据库系统)集成在一起,当上架一台新机器的时候CMDB里面会记录相关的信息,Zabbix根据CMDB里面信息自动Link相关的模块,添加|删除监控.很多小的公司没有资产管理系统,但作为监控的负责人应该每天知道上架了哪些新的机器,确保能添加到Zabbix监控里面.    首先给大家说一下脚本思路:1)通过Nmap工具

Appium+python自动化8-Appium Python API

前言: Appium Python API全集,不知道哪个大神整理的,这里贴出来分享给大家. 1.contexts contexts(self): Returns the contexts within the current session. 返回当前会话中的上下文,使用后可以识别H5页面的控件 :Usage: driver.contexts 用法 driver.contexts 2. current_context current_context(self): Returns the cur

Openstack python api 学习文档

Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack,所以上一篇写了一些使用openstack的纯api调用的方法, 但是openstack还提供了更好的python的api,只需要python的包即可,感觉更好使用. 对于compute的api,包是放在了/usr/lib/python2.7/site-packages/novaclient/目录,