bitbucket基于commit事件的自动发布

来源:互联网 发布:淘宝回收手机吗 编辑:程序博客网 时间:2024/06/05 18:02

起因

公司有一个频繁迭代的项目,每日的提交量有20个左右。每次想要看到变更后的效果,都要ssh进入服务器,先git pull,再restart服务,颇为麻烦。

思考

手动发布代码既麻烦又存在操作不及时、操作失误等问题。于是我想到了持续集成系统,如Jenkins。不过这套系统对于本项目来说有点杀鸡用牛刀了,而且费资源。
我找到了bitbucket中的Webhooks的介绍:

Webhooks allow you to extend what Bitbucket does when the repository changes (for example, new code is pushed or a pull request is merged).

意思是说对代码进行读写操作的时候可以执行一些自定义动作,如下图:
webhooks

我们只需绑定Push事件即可,URL填入自己搭建的service(稍后介绍),一旦有对应事件产生,则会访问URL,那么此时就可以触发自动更新代码的逻辑了。

实现service

核心实现

Bitbucket提供了对应文档,这里只看Push事件的文档。Show request body按钮提供了请求数据的样本。
下面附上匹配当前分支事件的代码

import jmespathdef match_branch(content, branch):    data = json.loads(content)    changes = jmespath.search('push.changes', data)    for change in changes or []:        commit_branch = jmespath.search('new.name', change)        if commit_branch and commit_branch == branch:            return True    return False

如果请求体被函数检测通过,那么就执行git pull,restart等行为。
这里附上基于flask web框架的demo

from flask import Flask, requestapp = Flask(__name__)BRANCH = 'master'@app.route('/autodeploy', methods=['POST'])def autodeploy():    if match_branch(request.data, BRANCH):        # TODO: 执行git pull,restart等行为        pass    else:        return 'ignore', 201if __name__ == '__main__':    app.run(host='0.0.0.0', port=8000)

BRANCH全局变量需要修改为自己项目对应的分支名,服务的URL为http://yourdomain.com:8000/autodeploy,将其填入Bitbucket的Webhooks中,那么下次代码从本地Push到服务器时,就自动发布。