#!/usr/bin/env python
# coding=utf-8
import os
import sys
libpath = os.path.join(os.path.dirname(__file__),'lib')
sys.path.insert(0,libpath)
from ansible import playbook, callbacks
import logging
import pprint
import time
DT=time.strftime('%Y%m%d')
TM=time.strftime('%H')
#import xlsxwriter
#workbook = xlsxwriter.Workbook('array_formula.xlsx')
def myprint(color,mes):
"""
用于打印颜色
:param color: 颜色
:param mes: 打印内容
:return: 没有返回
"""
"""
30: 黑色
31: 红色
32: 绿色
33: 黄色
34: 蓝色
35: 紫色
36: 深绿色
37: 白色
"""
info = {'red':31, 'green': 32, 'yellow':33, 'blue':34,'dark_green':36,'default':37}
if color in info:
fore = info[color]
else:
fore = 37
color = "\x1B[%d;%dm" % (1,fore)
print("%s%s\x1B[0m" % (color,mes))
class LoggingCallbacks(callbacks.PlaybookCallbacks):
def log(self, level, msg, *args, **kwargs):
logging.log(level, msg, *args, **kwargs)
print msg
def on_task_start(self, name, is_conditional):
#self.log(
logging.INFO, 'task: {0}'.format(name))
#super(LoggingCallbacks, self).on_task_start(name, is_conditional)
#la.append('name')
resall=u'TASK:'+name+'*'*40+'\n'
myprint("default",resall)
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-ok.txt', 'a') as f:
f.write(resall)
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-error.txt', 'a') as f:
f.write(resall)
class LoggingRunnerCallbacks(callbacks.PlaybookRunnerCallbacks):
def log(self, level, msg, *args, **kwargs):
logging.log(level, msg, *args, **kwargs)
def _on_any(self, level, label, host, orig_result):
result = orig_result.copy()
result.pop('invocation', None)
result.pop('verbose_always', True)
item = result.pop('item', None)
if not result:
msg = ''
elif len(result) == 1:
msg = ' | {0}'.format(result.values().pop())
else:
msg = '\n' + pprint.pformat(result)
if item:
self.log(level, '{0} (item={1}): {2}{3}'.format(host, item, label, msg))
else:
self.log(level, '{0}: {1}{2}'.format(host, label, msg))
def on_failed(self, host, res, ignore_errors=False):
if ignore_errors:
level =
logging.INFO label = 'FAILED (ignored)'
else:
level = logging.ERROR
label = 'FAILED'
self._on_any(level, label, host, res)
super(LoggingRunnerCallbacks, self).on_failed(host, res, ignore_errors)
resall=host+ u'\nFAILED:\n{0}'+format(res['stderr'])
myprint("red",resall)
myprint("red",res['stdout']+'\n'+'\n')
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-error.txt', 'a') as f:
f.write(resall)
f.write(res['stdout']+'\n'+'\n')
def on_ok(self, host, res):
#self._on_any(
logging.INFO, 'SUCCESS', host, res)
super(LoggingRunnerCallbacks, self).on_ok(host, res)
#print host,res
resall=host+ u'\n'+format(res['stdout'])
myprint("green",resall)
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-ok.txt', 'a') as f:
f.write(resall+'\n')
def on_error(self, host, msg):
self.log(logging.ERROR, '{0}: ERROR | {1}'.format(host, msg))
super(LoggingRunnerCallbacks, self).on_error(host, msg)
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-error.txt', 'a') as f:
f.write(str(host)+'\n')
f.write(str(msg)+'\n')
def on_skipped(self, host, item=None):
if item:
self.log(
logging.INFO, '{0} (item={1}): SKIPPED'.format(host, item))
else:
self.log(
logging.INFO, '{0}: SKIPPED'.format(host))
super(LoggingRunnerCallbacks, self).on_skipped(host, item)
def on_unreachable(self, host, res):
#self._on_any(logging.ERROR, 'UNREACHABLE', host, dict(unreachable=res))
super(LoggingRunnerCallbacks, self).on_unreachable(host, res)
resall=host+ u'\nERROR:CONNECT FAILD:\n{0}\n'+format(res)
myprint("red",resall+'\n')
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-error.txt', 'a') as f:
f.write(resall+'\n')
def on_no_hosts(self):
self.log(logging.ERROR, 'No hosts matched')
super(LoggingRunnerCallbacks, self).on_no_hosts()
def run_playbook(name):
if not os.path.exists('/root/ans/log/'+DT):
os.mkdir('/root/ans/log/'+DT)
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-ok.txt', 'w') as f:
f.write('Today is '+DT+' Let the check begin'+'\n\n')
with open('/root/ans/log/'+DT+'/'+TM+'-'+sys.argv[1]+'-error.txt', 'w') as f:
f.write('Today is '+DT+' Let the check begin'+'\n\n')
stats = callbacks.AggregateStats()
playbook_cb = LoggingCallbacks(verbose=3)
runner_cb = LoggingRunnerCallbacks(stats, verbose=3)
pb = playbook.PlayBook(
playbook=name,
stats=stats,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
)
pb.run()
if __name__ == "__main__":
run_playbook(sys.argv[1])