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類,盡請期待
執行結果部分內容