Ansible的runner源码剖析第一部分
版本ansible1.9.1
(1)这部分只讲简单使用例子
test.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
##################
import ansible.runner
##########################
runner = ansible.runner.Runner(
host_list = 'ip.txt', #指定主机文件
remote_user = 'root', #指定远程执行用户
module_name = 'shell', #使用ansible的shell
module_args = 'echo 111', #模块参数
pattern = 'test', #主机文件中生效的组
forks = 5, #多进程并发数量
remote_pass = '123456', #远程执行的密码
#is_playbook= True,
)
datastructure = runner.run()
print anyalize_result(datastructure)
ip.txt
[test]
192.168.1.1
192.168.1.2
对远程主机执行shell命令echo 111,datastructure呢是ansible结果处理后的结果
(2)ansible跑完的结果处理nyalize_result函数
#处理连接失败,认证失败及执行失败的多种不同情况的数据分类汇总
import json
def anyalize_result(datastructure):
#传递进来任务ID,以及ansible执行结果进行处理
ret = dict()
ret['task_id'] = 66666
ret['AuthenticationFailed'] = list()
ret['ConnectedFailed'] = list()
ret['failed'] = list()
fail_temp = datastructure.get('dark',None)
if fail_temp:
for ip,value in fail_temp.items():
msg = str(value.get('msg',None)).replace('\n','|')
if 'Authentication failure' in msg:
ret['AuthenticationFailed'].append({ip:msg})
elif 'timed out' in msg:
ret['ConnectedFailed'].append({ip:msg})
elif 'Connection refused' in msg:
ret['ConnectedFailed'].append({ip:msg})
elif 'Connection closed' in msg:
ret['ConnectedFailed'].append({ip:msg})
else:
ret['failed'].append({ip:msg})
ret['success'] = list()
succ_temp = datastructure.get('contacted',None)
if succ_temp:
for ip,result in succ_temp.items():
result_temp = result.get('stderr',None)
if not result_temp:
ret['success'].append({ip:str(result.get('stdout',None)).replace('\n','|')})
else:
ret['failed'].append({ip:str(result_temp).replace('\n','|')})
return json.dumps(ret,indent=4)
结果么,自然优雅的很,像如下内容;自己试试吧,加油
# 第二部分会源码剖析runner类,尽请期待