环境
centos7
ansible 2.9.10-1.el7(yum安装)
python2.7
背景
使用ansible-playbook批量执行工具,但发现ansible能返回显示执行结果,ansible-playbook只会返回ok/change/fail,对于需要检查返回结果就还要到机器上二次确认,比较麻烦。所以研究了下ansible-playbook结果回显的方法。
ansible-playbook例子:对主机执行date,返回日期
---
- hosts: test #定义需要执行主机
remote_user: root #远程用户
tasks:
- name: test
shell: date
正常不回显结果:
方法一:
对单条任务结果回显:为这条任务加个regiter,并新加另一个任务show结果出来
---
- hosts: test #定义需要执行主机
remote_user: root #远程用户
tasks:
- name: test
shell: date
register: check
- name: show
debug: var=check verbosity=0 #check.stdout 显示出的信息会看的更清晰点
结果变化:
方法二:
执行的时候加参数--verbose
ansible-playbook -i hosts playbook-test.yaml --verbose
结果变化:
方法三:
加插件的方式,在/etc/ansible/ansible.cfg里修改callback_plugins = /etc/ansible/callbacks
并编写插件文件在/etc/ansible/callbacks/showlog.py
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import json
from ansible.plugins.callback import CallbackBase
######################
class CallbackModule(CallbackBase):
#执行成功的
def v2_runner_on_ok(self, result, **kwargs):
host = result._host
print (host.name,result._result['stderr_lines'],result._result['stdout_lines'])
#执行失败的
def runner_on_failed(self, host, res, ignore_errors=False):
pass
#执行跳过的
def runner_on_skipped(self, host, item=None):
pass
#主机不可达的
def runner_on_unreachable(self, host, res):
pass
结果变化:
来源:oschina
链接:https://my.oschina.net/u/3950034/blog/4698199