Jenkins之自動發送git變更到微信


      當我們通過Jenkins構建job的時候,是可以獲取到git Change Log 的信息, 即本次上線修改了什么功能,我們將這個信息發送到微信群相關人員可直接獲取到上線變更信息,

這樣就不需要人為的去通告,以下是效果圖:

              

 

主要用到的這個插件: https://github.com/daniel-beck/changelog-environment-plugin

核心配置: 

 

我這里使用的是 項目構建完成后 使用Post build task  調用一個發送的腳本,這個腳本會將信息發送到對應微信群,

你也可以通過其它的方式,只要能將消息發出去:

 

微信發送腳本代碼:

#!/usr/bin/python2.7
#_*_coding:utf-8 _*_


import requests,sys,json
import urllib3
urllib3.disable_warnings()

reload(sys)
sys.setdefaultencoding('utf-8')

def GetToken(Corpid,Secret):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    Data = {
        "corpid":Corpid,
        "corpsecret":Secret
    }
    r = requests.get(url=Url,params=Data,verify=False)
    Token = r.json()['access_token']
    return Token

def SendMessage(Token,Subject,Content, ProName):
    Url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=%s" % Token
    Data = {
        "chatid": "JenkinsAlarm",  # 此處不明白請參考企業微信官網
        "msgtype": "text",
        "text": {
            "content": "[項目名稱] : " + ProName + '\n' + "[項目地址] : " + Subject + '\n' + Content + '\n'
        },
        "safe": "0"
    }
    r = requests.post(url=Url,data=json.dumps(Data),verify=False)
    return r.text

def action_from_file(filename):
    try:
        str1 = '[變更日志] : '
        with open(filename, 'r') as f:
            for i in f.readlines():
                str1 += i
        if len(str1) == 17:
            str1 += " 無變更"
        return str1
    except Exception as e:
        print('[ERROR] {0}'.format(e))


if __name__ == '__main__':
    Corpid = "xxxx"
    Secret = "xxxxxxxxx"

    Subject = sys.argv[1]
    Content = action_from_file(sys.argv[2])
    ProName = sys.argv[3]

    Token = GetToken(Corpid, Secret)
    Status = SendMessage(Token,Subject,Content,ProName)
    print Status

   

以上是正常的通過每個Job內配置的git地址獲取的方式。

 

但是我們這里有個k8s的pipeline配置,pipeline里面無法使用上面的插件,我通過編寫腳本實現了如上一樣的功能:

大體思路如下:

    1.  獲取當前 commit_id  , 獲取上次 commit_id , 通過git命令取到兩次commit_id之間的日志並發送

    2. 我是將commit_id 存到redis,每次更新commit_id , 項目第一次構建的話會取前兩行發送,之后則正常

代碼如下

#!/bin/bash

BaseDir=$1
Project=$2
Joburl=$3
Branch=$4

if [[ $Branch != master ]]; then
   echo "Not master, exit..."
   exit 0
fi


last_commit_id=$(/usr/bin/redis-cli -h 192.168.111.152 get $Project)

cd $BaseDir && curr_commit_id=$(git log HEAD -1 --pretty=format:'%H')

if [[ $last_commit_id == "" ]] ; then
   cd $BaseDir
   msg=$(git log --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%s (at %cd via %cn)'|head -2)
   echo "$msg" > /tmp/build_msg

elif [[ $last_commit_id == ${curr_commit_id} ]] ; then
   msg="(無變更)"
   echo "(無變更)" > /tmp/build_msg

else
   msg=`git log --date=format:"%Y-%m-%d %H:%M:%S" --pretty=format:"%s (at %cd via %cn)" ${last_commit_id}..${curr_commit_id}`
   echo "$msg" > /tmp/build_msg
fi

/usr/bin/redis-cli -h 192.168.111.152 set $Project $curr_commit_id

#python /root/auto_falcon/jenkins_notify.py $Project /tmp/build_msg  $Joburl

grep -v Merge /tmp/build_msg|cat -n > /tmp/send_msg


curr_date=$(date "+%Y/%m/%d %H:%M:%S")
change_log=$(cat /tmp/send_msg)
Content="[構建時間] : ${curr_date} \n[項目名稱] : ${Project} \n[項目地址] : ${Joburl}\n[變更日志] :${change_log}"
CropID="xxxx"
Secret="xxxxx"
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F\" '{print $10}')
PURL="https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=$Gtoken"

/usr/bin/curl --data-ascii '{ "chatid": "jenkinsAlarm", "msgtype": "text","text": {"content": "'"${Content}"'"},"safe":"0"}' $PURL

  

 

 

 

參考網址:

     1. https://www.jianshu.com/p/f03fc1bf5783 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM