Ansible - 使用CallBack + 如何自定义Callback

开启 callback 功能,在callback_whitelist 中添加

vim ansible.cfg

callback_plugins   = plugins/callback

# by default callbacks are not loaded for /bin/ansible, enable this if you
# want, for example, a notification or logging callback to also apply to
# /bin/ansible runs
bin_ansible_callbacks = Ture 

# Uncomment below to profile an anible run i.e. how long tasks take
#callback_whitelist = profile_tasks
callback_whitelist = XXX, XXX, XXX

ansible 自带哪些 callback 功能。

actionable – shows only items that need attention
aws_resource_actions – summarizes all “resource:actions” completed
cgroup_memory_recap – Profiles maximum memory usage of tasks and full execution using cgroups
cgroup_perf_recap – Profiles system activity of tasks and full execution using cgroups
context_demo – demo callback that adds play/task context
counter_enabled – adds counters to the output items (tasks and hosts/task)
debug – formatted stdout/stderr display
default – default Ansible screen output
dense – minimal stdout output
foreman – Sends events to Foreman
full_skip – suppresses tasks if all hosts skipped
grafana_annotations – send ansible events as annotations on charts to grafana over http api
hipchat – post task events to hipchat
jabber – post task events to a jabber server
json – Ansible screen output as JSON
junit – write playbook output to a JUnit file
log_plays – write playbook output to log file
logdna – Sends playbook logs to LogDNA
logentries – Sends events to Logentries
logstash – Sends events to Logstash
mail – Sends failure events via email
minimal – minimal Ansible screen output
nrdp – post task result to a nagios server through nrdp
null – Don’t display stuff to screen
oneline – oneline Ansible screen output
osx_say – notify using software speech synthesizer
profile_roles – adds timing information to roles
profile_tasks – adds time information to tasks
say – notify using software speech synthesizer
selective – only print certain tasks
skippy – Ansible screen output that ignores skipped status
slack – Sends play events to a Slack channel
splunk – Sends task result events to Splunk HTTP Event Collector
stderr – Splits output, sending failed tasks to stderr
sumologic – Sends task result events to Sumologic
syslog_json – sends JSON events to syslog
timer – Adds time to play stats
tree – Save host events to files
unixy – condensed Ansible output
yaml – yaml-ized Ansible screen output

如果使用系统自带的callback,需要将需要的参数写入 ansible.cfg。

 

自定义 callback

如果要编写自定义的callback,要将脚本写入到 plugins/callback,并将路径配置到 ansible.cfg

我们写一个当执行结束之后,将执行语句和结果记录到 PG 数据库中的 callback

1. 建文件,基本内容

vim plugins/callback/

# 版本
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
# 描述
DOCUMENTATION = """
---
    callback: 
    callback_type: notification
    requirements:
      - packages.
    short_description: short description for the callback plugin.
    description:
        - There is description for this callback plugin.
    author: "chuckchen1222@gmail.com"
"""
# 继承
from ansible.plugins.callback import CallbackBase
# 创建类,继承callbackbase 
# 开始
class CallbackModule(CallbackBase):
    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'notification' #TODO what's a callback type, setting to notification for now because why not I guess? change in DOCUMENTATION as well
    CALLBACK_NAME = 'ta_host_locking'

    def __init__(self):
        super(CallbackModule, self).__init__()
        self.lock_results = None

2. 操作执行

接下来是我们要做什么,比如我们要在执行之后,将信息添加到数据库中。

    def logging_to_db(self, stat):
        sql = 'INSERT INTO test(col1, col2, ctime) VALUES (\'%s\', \'%s\', now());' % (self.cmd , stat)
        conn = psycopg2.connect(database='mytest', user='mytest', host='dbwtest03bc.daodao.com')
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()

3. 什么情况下做

v2_on_any(self, *args, **kwargs):
v2_runner_on_failed(self, result, ignore_errors=False):
v2_runner_on_ok(self, result):
v2_runner_on_skipped(self, result):
v2_runner_on_unreachable(self, result):
v2_runner_on_async_poll(self, result):
v2_runner_on_async_ok(self, result):
v2_runner_on_async_failed(self, result):
v2_playbook_on_start(self, playbook):
v2_playbook_on_notify(self, handler, host):
v2_playbook_on_no_hosts_matched(self):
v2_playbook_on_no_hosts_remaining(self):
v2_playbook_on_task_start(self, task, is_conditional):
v2_playbook_on_cleanup_task_start(self, task):
v2_playbook_on_handler_task_start(self, task):
v2_playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None, unsafe=None):
v2_playbook_on_import_for_host(self, result, imported_file):
v2_playbook_on_not_import_for_host(self, result, missing_file):
v2_playbook_on_play_start(self, play):
v2_playbook_on_stats(self, stats):
v2_on_file_diff(self, result):
v2_playbook_on_include(self, included_file):
v2_runner_item_on_ok(self, result):
v2_runner_item_on_failed(self, result):
v2_runner_item_on_skipped(self, result):
v2_runner_retry(self, result):
v2_runner_on_start(self, host, task):

在源码 plugins/callback/__init__.py 中,有这些触发事件。

我们可以在这里 overwrite ,控制事件的触发。

    def v2_runner_on_ok(self, result):
        print (result.__dict__.items())
        self.logging_to_db(result=result, stat='ok')


    def playbook_on_stats(self, stats):
        if stats:
            print (stats.__dict__.items())
            hosts = sorted(stats.processed.keys())
            for h in hosts:
                s = stats.summarize(h)
                print (s)
            print (stats.custom.key())

 

4. 可以获取的信息

4.1. result

result._host: 主机名

result._task:任务名

result._result:结果

result._task_fields:执行信息

 

4.2 stats

stats.__dict__.items()

[('processed', {'dbw21as': 1}), ('failures', {'dbw21as': 1}), ('ok', {'dbw21as': 3}), ('dark', {}), ('changed', {}), ('skipped', {}), ('rescued', {}), ('ignored', {}), ('custom', {})]

for h in hosts:
    t = stats.summarize(h)

 

 

 

 

 

 

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值