Ansible 开发API 之【使用api运行task任务】

ansible 依赖于子进程,因此API不是线程安全的。

环境


本文使用的是ansible api 2.0
ansible 2.3.0.0
os Centos 6.7 X64
python 2.6.6

下面是一个执行task的例子

主机清单


task任务执行的主机

~]# cat /etc/ansible/hosts
[node1]
192.168.77.129 ansible_ssh_pass=123456

api


~]# cat test.py 
#!/bin/env python
#! coding: utf-8

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.executor.task_result import TaskResult
from ansible.plugins.callback import CallbackBase

# 自定义 callback,即在运行 api 后调用本类中的 v2_runner_on_ok(),在这里会输出 host 和 result 格式
class ResultCallback(CallbackBase):
    def v2_runner_on_ok(self, result, **kwargs):
        # result 包含 '_check_key', '_host', '_result', '_task', '_task_fields', 'is_changed', 'is_failed', 'is_skipped', 'is_unreachable', 'task_name'
        host = result._host
        print u"%s 执行结果" % result._task
        print json.dumps({host.name: result._result}, indent=4)
        print "-----------------------------------------------"

# 初始话需要的类
variable_manager = VariableManager()
# 用来管理变量,包括主机、组、扩展等变量,该类在之前的Inventory内置

loader = DataLoader()
# 用来加载解析yaml文件或JSON内容,并且支持vault的解密

# 定义选项 
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check'])

# 定义连接远端的额方式为smart
options = Options(connection='smart', module_path=None, forks=100, become=None, become_method=None, become_user=None, check=False)

# 定义默认的密码连接,主机未定义密码的时候才生效,conn_pass指连接远端的密码,become_pass指提升权限的密码
passwords = dict(conn_pass='123456', become_pass='123456')

# Instantiate our ResultCallback for handling results as they come in
# 结果回调类实例化
results_callback = ResultCallback()

# create inventory and pass to var manager
# 创建inventory、并带进去参数
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='/etc/ansible/hosts')  
# hosts文件,也可以是 ip列表 '10.1.162.18:322, 10.1.167.36' 或者 ['10.1.162.18:322', '10.1.167.36'],如果不设置,默认取ansible.cfg配置文件中的inventory值,默认为/etc/ansible/hosts.
variable_manager.set_inventory(inventory)
# 把inventory传递给variable_manager管理

# create play with tasks
# 创建要执行play的内容并引入上面的变量
play_source =  dict(
        name = "Ansible Play", 
        hosts = 'node1',   # 匹配host_list中的主机的正则表达式
        gather_facts = 'no',
    # 定义任务列表
        tasks = [
            dict(action=dict(module='shell', args='hostname'), register='shell_out',async=0,poll=15),
            dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')),async=0,poll=15)
         ]
    )

play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

# actually run it
# TaskQueueManager 是创建进程池,负责输出结果和多进程间数据结构或者队列的共享协作
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
              # 如果注释掉 callback 则会调用原生的 DEFAULT_STDOUT_CALLBACK,输出 task result的output,同 ansible-playbook debug
          )
    result = tqm.run(play)
    print u'任务执行返回码: %s' % result  # 返回码,只要有一个 host 出错就会返回 非0 数字
finally:
    if tqm is not None:
        tqm.cleanup()
    if loader:
        print 'end'    
        loader.cleanup_all_tmp_files()
    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

执行结果


~]# python test.py 
TASK: command 执行结果
{
    "192.168.77.129": {
        "_ansible_parsed": true, 
        "stderr_lines": [], 
        "cmd": "hostname", 
        "end": "2017-06-22 17:52:18.111433", 
        "_ansible_no_log": false, 
        "stdout": "node1", 
        "changed": true, 
        "rc": 0, 
        "start": "2017-06-22 17:52:18.109322", 
        "stderr": "", 
        "delta": "0:00:00.002111", 
        "invocation": {
            "module_args": {
                "warn": true, 
                "executable": null, 
                "_uses_shell": true, 
                "_raw_params": "hostname", 
                "removes": null, 
                "creates": null, 
                "chdir": null
            }
        }, 
        "stdout_lines": [
            "node1"
        ]
    }
}
-----------------------------------------------
TASK: debug 执行结果
{
    "192.168.77.129": {
        "msg": "node1", 
        "changed": false, 
        "_ansible_verbose_always": true, 
        "_ansible_no_log": false
    }
}
-----------------------------------------------
任务执行返回码: 0

TaskQueueManager 字段说明


inventory --> 由ansible.inventory模块创建,用于导入inventory文件
variable_manager --> 由ansible.vars模块创建,用于存储各类变量信息
loader --> 由ansible.parsing.dataloader模块创建,用于数据解析
options --> 存放各类配置信息的数据字典
passwords --> 登录密码,可设置加密信息
stdout_callback --> 回调函数

TaskQueueManager.run方法的返回状态码


RUN_OK                = 0    
RUN_ERROR             = 1  
RUN_FAILED_HOSTS      = 2
RUN_UNREACHABLE_HOSTS = 4
RUN_FAILED_BREAK_PLAY = 8
RUN_UNKNOWN_ERROR     = 255
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容