Python 调用 Ansible API 简例

如下是ad-hoc模式下的调用方式:ansible [模块] [选项] [主机资产]

#!/usr/bin/env python

import json
import shutil
from collections import namedtuple
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
import ansible.constants as C

#重写执行结果返回的类,使返回的对象为json类型
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
    """
    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
        """
        host = result._host
        print(json.dumps({host.name: result._result}, indent=4))

#[设置选项] since API is constructed for CLI it expects certain options to always be set, named tuple ‘fakes‘ the args parsing options object
Options = namedtuple(‘Options‘, [‘connection‘, ‘module_path‘, ‘forks‘, ‘become‘, ‘become_method‘, ‘become_user‘, ‘check‘, ‘diff‘])
options = Options(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
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/hosts1‘)

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

# create datastructure that represents our play, including tasks, this is basically what our YAML loader does internally.这里设置使用什么模块
play_source =  dict(
        name = "Ansible Play",
        hosts = ‘192.168.60.71‘,
        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}}‘)))
         ]
    )

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

#[ 设置任务队列并运行 ] 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,
              options=options,
              passwords=passwords,
              stdout_callback=results_callback,  # 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 structres we use to communicate with them
    if tqm is not None:
        tqm.cleanup()

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

参考Ansible 官方文档

原文地址:http://blog.51cto.com/jackor/2340389

时间: 2024-08-26 02:54:49

Python 调用 Ansible API 简例的相关文章

Python调用ansible API系列(四)动态生成hosts文件

方法一:通过最原始的操作文件的方式 #!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过操作文件形式动态生成ansible的hosts文件 """ import sys class Inventory: def __init__(self): # ansible的hosts文件路径 self._hostsfile = "./aaa" self._data = self._ge

Python调用微博API

上头叫通过微博ID获取用户发布过的历史微博内容,于是研究了下新浪微博提供的API 1 首先在微博开放中心下"创建应用"创建一个应用,应用信息那些随便填,填写完毕后,不需要提交审核,需要的只是那个app-key和app-secret 2 在"微博开放平台"的"管理中心"找到刚才创建的应用,点开这个应用,点开左边"应用信息"栏,会看见"App key"和"App Secret"的字样,这两个

使用Python调用Flickr API抓取图片数据

Flickr是雅虎旗下的图片分享网站,上面有全世界网友分享的大量精彩图片,被认为是专业的图片网站.其API也很友好,可以实现多种功能.这里我使用了Python调用其API获得了大量的照片数据. 首先需要先去Flickr注册成为其开发者,创建应用,获得API_KEY和API_SECRET,其API网址在:https://www.flickr.com/services/api/ Flickr提供了多种开发工具进行使用.这里我们使用Python开发工具.官方推荐的开发工具是Beej’s Python

Java 远程调用之Hessian简例

1. [代码]1.服务接口(Hello.java) package server; public interface Hello { String hello(String name);}2. [代码]2.接口实现(HelloImpl.java) package server; public class HelloImpl implements Hello{ public String hello(String name) {    return "hello,"+name+"

python 调用zabbix api实现查询主机信息,输出所有主机ip

之前发现搜索出来的主机调用zabbix api信息都不是那么明确,后来通过zabbix官方文档,查到想要的api信息,随后写一篇自己这次项目中用到的api. #!/usr/bin/env python #coding:utf8 import requests import json headers = {'Content-Type': 'application/json-rpc'} server_ip = '10.37.149.109' url = 'http://%s/zabbix/api_j

python调用zabbix api接口实时展示数据

近日公司准备自已做一个运维管理平台,其中的监控部分,打算调用zabbix api接口来进行展示. 经过思考之后,计划获取如下内容: 1.  获得认证密钥 2.  获取zabbix所有的主机组 3.  获取单个组下的所有主机 4.  获取某个主机下的所有监控项 5.  获取某个监控项的历史数据 6.  获取某个监控项的最新数据 计划最后展示框架如下内容(这只是值方面,其它的会再加): 主机组1 ----主机名1---监控项1----当前值 ---监控项2----当前值 ----主机名2----监控

(二)Python调用Zabbix api之从入门到放弃——登录并获取身份验证令牌

访问zabbix api的URL是: http://x.x.x.x/zabbix/api_jsonrpc.php x.x.x.x可能是你的IP或者域名 访问流程概览: 1.首先登录 2.认证成功后zabbix server返回一个token 3.带着这个token去访问各种数据,做各种操作 4.完毕! 一.用RESTClient进行登录 在json请求的正文中,具有以下属性: jsonrpc - API使用的JSON-RPC协议的版本; Zabbix API实现JSON-RPC版本2.0; me

Python调用Windows API函数编写录音机和音乐播放器

功能描述: 1)使用tkinter设计程序界面: 2)调用Windows API函数实现录音机和音乐播放器. . 参考代码: ? 运行界面: ? 原文地址:https://www.cnblogs.com/7758520lzy/p/12149931.html

Python 调用cobbler API 学习笔记

目前BootAPI 已经不再推荐在cobbler 2.0中使用,官方推荐使用使用XMLRPC 注:要正常使用API,需要确保cobbler服务器apache和cobbler正常运行 连接cobbler import xmlrpclib server = xmlrpclib.Server("http://cobbler-server.example.org/cobbler_api") 登陆获取token,这个token在修改cobbler对象的时候需要提供,否则只能get token =