營運工具ansible調用callbacks實現結果nosql回調

來源:互聯網
上載者:User

前言:

ansible的結果預設是輸出到cli終端和日誌裡面的,用慣了saltsatck的returners資料回調後,也很是喜歡ansible也有,一開始不知道有這個功能,自己也簡單實現了這樣的功能。


我的實現方式是,在模組裡面做一些輸出的邏輯。當使用ansible runner api的時候,是在後面runner代碼,最後加了一段往redis輸出的邏輯。 這裡實現資料的輸出有些獨特,但是只能是在模組和 api方面搞 。 如果是用playbook的話,按照我以前的思路的話,再繼續改ansbile的源碼。  這兩天聽沈燦說,ansible有個callback_plugins的功能,可以對於執行的狀態做一些判斷,比如,執行成功,執行失敗,非同步執行,非同步執行失敗,playbook開始,結束等等。

我也不說複雜了,就簡單說一個例子,把執行的結果,都推到redis裡面,也可以暫存到sqlite資料庫裡面,只是這段代碼我給屏蔽了,有興趣的朋友再搞搞。對於redis裡面的資料可以寫一個頁面展現下,專門記錄錯誤的問題,成功的就pass掉。

 代碼如下 複製代碼
#xiaorui.cc
 
import os
import time
import sqlite3
import redis
import json
 
dbname = '/tmp/setup.db'
TIME_FORMAT='%Y-%m-%d %H:%M:%S'
 
try:
    con = sqlite3.connect(dbname)
    cur = con.cursor()
except:
    pass
 
def log(host, data):
 
#    if type(data) == dict:
#        invocation = data.pop('invocation', None)
#        if invocation.get('module_name', None) != 'setup':
#            return
#
#    facts = data.get('ansible_facts', None)
#
#    now = time.strftime(TIME_FORMAT, time.localtime())
#
#    try:
#        # `host` is a unique index
#        cur.execute("REPLACE INTO inventory (now, host, arch, dist, distvers, sys,kernel) VALUES(?,?,?,?,?,?,?);",
#        (
#            now,
#            facts.get('ansible_hostname', None),
#            facts.get('ansible_architecture', None),
#            facts.get('ansible_distribution', None),
#            facts.get('ansible_distribution_version', None),
#            facts.get('ansible_system', None),
#            facts.get('ansible_kernel', None)
#        ))
#        con.commit()
#    except:
#        pass
#
class CallbackModule(object):
    def runner_on_ok(self, host, res):
        r = redis.Redis(host='127.0.0.1', port=6379, db=0)
        r.set(host,str(res))
 
        f = open('/tmp/11','a')
        f.write(str(host))
        f.write(str(res))
        f.close()
        log(host, res)
    def runner_on_failed(self, host, res, ignore_errors=False):
        f = open('/tmp/11','a')
        f.write('nbadn')
        f.close()
        log(host, res)

 



還是可以接收所有的facts資料的。

雖然我上面的例子用了redis,sqlite資料庫,其實我個人推薦用mongodb這樣的文檔資料庫的。因為ansible主runner函數,給callbacks傳遞了一個叫res的變數,他本身就是一個dict對象,如果放到redis的hash,sqlite的各種欄位,夠你煩的了,如果直接mongo,那就簡單了,直接insert ! 歐了




這裡在show一個郵件的callbacks代碼,情境是,非常消耗時間的任務,當執行完成後,查看結果咋辦?  但是你也可以在終端繼續看,既然咱們講了callbacks_plugins,就可以把結果push到你的郵箱裡面,當然只給你發錯誤的,有問題的。 下面的callback代碼需要自己替換成自己用的郵箱、密碼、smtp伺服器。

 代碼如下 複製代碼
#xiaorui.cc

 
import smtplib
 
def mail(subject='Ansible error mail', sender='<root>', to='root', cc=None, bcc=None, body=None):
    if not body:
        body = subject
 
    smtp = smtplib.SMTP('localhost')
 
    content = 'From: %sn' % sender
    content += 'To: %sn' % to
    if cc:
        content += 'Cc: %sn' % cc
    content += 'Subject: %snn' % subject
    content += body
 
    addresses = to.split(',')
    if cc:
        addresses += cc.split(',')
    if bcc:
        addresses += bcc.split(',')
 
    for address in addresses:
        smtp.sendmail(sender, address, content)
 
    smtp.quit()
 
 
class CallbackModule(object):
 
    """
    This Ansible callback plugin mails errors to interested parties.
    """
 
    def runner_on_failed(self, host, res, ignore_errors=False):
        if ignore_errors:
            return
        sender = '"Ansible: %s" <root>' % host
        subject = 'Failed: %(module_name)s %(module_args)s' % res['invocation']
        body = 'The following task failed for host ' + host + ':nn%(module_name)s %(module_args)snn' % res['invocation']
        if 'stdout' in res.keys() and res['stdout']:
            subject = res['stdout'].strip('rn').split('n')[-1]
            body += 'with the following output in standard output:nn' + res['stdout'] + 'nn'
        if 'stderr' in res.keys() and res['stderr']:
            subject = res['stderr'].strip('rn').split('n')[-1]
            body += 'with the following output in standard error:nn' + res['stderr'] + 'nn'
        if 'msg' in res.keys() and res['msg']:
            subject = res['msg'].strip('rn').split('n')[0]
            body += 'with the following message:nn' + res['msg'] + 'nn'
        body += 'A complete dump of the error:nn' + str(res)
        mail(sender=sender, subject=subject, body=body)
                  
    def runner_on_unreachable(self, host, res):
        sender = '"Ansible: %s" <root>' % host
        if isinstance(res, basestring):
            subject = 'Unreachable: %s' % res.strip('rn').split('n')[-1]
            body = 'An error occured for host ' + host + ' with the following message:nn' + res
        else:
            subject = 'Unreachable: %s' % res['msg'].strip('rn').split('n')[0]
            body = 'An error occured for host ' + host + ' with the following message:nn' +
                   res['msg'] + 'nnA complete dump of the error:nn' + str(res)
        mail(sender=sender, subject=subject, body=body)
 
    def runner_on_async_failed(self, host, res, jid):
        sender = '"Ansible: %s" <root>' % host
        if isinstance(res, basestring):
            subject = 'Async failure: %s' % res.strip('rn').split('n')[-1]
            body = 'An error occured for host ' + host + ' with the following message:nn' + res
        else:
            subject = 'Async failure: %s' % res['msg'].strip('rn').split('n')[0]
            body = 'An error occured for host ' + host + ' with the following message:nn' +
                   res['msg'] + 'nnA complete dump of the error:nn' + str(res)
        mail(sender=sender, subject=subject, body=body)



如果不想發郵件,又不想搞到資料庫裡面,怎麼辦? 那來點低端的。  直接寫入到檔案裡面。

官方給出一個例子,大家照著模板寫就行了。

 代碼如下 複製代碼
import os
import time
import json
 
TIME_FORMAT="%b %d %Y %H:%M:%S"
MSG_FORMAT="%(now)s - %(category)s - %(data)snn"
 
if not os.path.exists("/var/log/ansible/hosts"):
    os.makedirs("/var/log/ansible/hosts")
 
def log(host, category, data):
    if type(data) == dict:
        if 'verbose_override' in data:
            # avoid logging extraneous data from facts
            data = 'omitted'
        else:
            data = data.copy()
            invocation = data.pop('invocation', None)
            data = json.dumps(data)
            if invocation is not None:
                data = json.dumps(invocation) + " => %s " % data
 
    path = os.path.join("/var/log/ansible/hosts", host)
    now = time.strftime(TIME_FORMAT, time.localtime())
    fd = open(path, "a")
    fd.write(MSG_FORMAT % dict(now=now, category=category, data=data))
    fd.close()
 
class CallbackModule(object):
    """
    logs playbook results, per host, in /var/log/ansible/hosts
    """
 
    def on_any(self, *args, **kwargs):
        pass
 
    def runner_on_failed(self, host, res, ignore_errors=False):
        log(host, 'FAILED', res)
 
    def runner_on_ok(self, host, res):
        log(host, 'OK', res)
 
    def runner_on_skipped(self, host, item=None):
        log(host, 'SKIPPED', '...')
 
    def runner_on_unreachable(self, host, res):
        log(host, 'UNREACHABLE', res)
 
    def runner_on_no_hosts(self):
        pass
 
    def runner_on_async_poll(self, host, res, jid, clock):
        pass
 
    def runner_on_async_ok(self, host, res, jid):
        pass
 
    def runner_on_async_failed(self, host, res, jid):
        log(host, 'ASYNC_FAILED', res)
 
    def playbook_on_start(self):
        pass
 
    def playbook_on_notify(self, host, handler):
        pass
 
    def playbook_on_no_hosts_matched(self):
        pass
 
    def playbook_on_no_hosts_remaining(self):
        pass
 
    def playbook_on_task_start(self, name, is_conditional):
        pass
 
    def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None):
        pass
 
    def playbook_on_setup(self):
        pass
 
    def playbook_on_import_for_host(self, host, imported_file):
        log(host, 'IMPORTED', imported_file)
 
    def playbook_on_not_import_for_host(self, host, missing_file):
        log(host, 'NOTIMPORTED', missing_file)
 
    def playbook_on_play_start(self, name):
        pass
 
    def playbook_on_stats(self, stats):
        pass







也可以把結果以webhooks鉤子的方式,做些你想做的東西。


callbacks的各種狀態還是很多的,每個函數的字眼還是很好理解的。

比如:

on_any  哪都有他 !任何的狀態他觸發。

runner_on_failed 失敗

runner_on_ok  成功

runner_on_unreachable 網路不可達

runner_on_no_hosts 沒有主機

runner_on_async_poll 任務的非同步執行

playbook_on_start  playbook執行的時候

等等。。。。  自己嘗試吧 !

 代碼如下 複製代碼
class CallbackModule(object):
 
 
    def on_any(self, *args, **kwargs):
        pass
 
    def runner_on_failed(self, host, res, ignore_errors=False):
        log(host, 'FAILED', res)
 
    def runner_on_ok(self, host, res):
        log(host, 'OK', res)
 
    def runner_on_skipped(self, host, item=None):
        log(host, 'SKIPPED', '...')
 
    def runner_on_unreachable(self, host, res):
        log(host, 'UNREACHABLE', res)
 
    def runner_on_no_hosts(self):
        pass
 
    def runner_on_async_poll(self, host, res, jid, clock):
        pass
 
    def runner_on_async_ok(self, host, res, jid):
        pass
 
    def runner_on_async_failed(self, host, res, jid):
        log(host, 'ASYNC_FAILED', res)
 
    def playbook_on_start(self):
        pass
 
    def playbook_on_notify(self, host, handler):
        pass
 
    def playbook_on_no_hosts_matched(self):
        pass
 
    def playbook_on_no_hosts_remaining(self):
        pass
 
    def playbook_on_task_start(self, name, is_conditional):
        pass
 
    def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None):
        pass
 
    def playbook_on_setup(self):
        pass
 
    def playbook_on_import_for_host(self, host, imported_file):
        log(host, 'IMPORTED', imported_file)
 
    def playbook_on_not_import_for_host(self, host, missing_file):
        log(host, 'NOTIMPORTED', missing_file)
 
    def playbook_on_play_start(self, name):
        pass
 
    def playbook_on_stats(self, stats):
        pass



咱們可以簡單看看ansible的callbacks源碼。

規定了兩個類,一個是供應ansible-playbook用的,還有一個是供應ansible,也就是cli。 根據各種的情況,調用不同的函數,首先會打到終端,再log日誌,最後是自訂的callbacks的外掛程式。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.