1. 程式人生 > 其它 >Jenkins:整合企業微信實現構建訊息推送

Jenkins:整合企業微信實現構建訊息推送

安裝外掛

http request plugin外掛

該外掛用於在Jenkinsfile中傳送http請求

build-user-vars-plugin外掛

該外掛用於在Jenkinsfile中獲取使用者名稱資訊

企業微信webhook

可以在企業微信的群組中新建一個機器人,名稱隨便

點選複製,拿到機器人的Webhook地址

編寫Jenkinsfile

獲取當前部署人

        wrap([$class: 'BuildUser']) {
            script {
                BUILD_USER = "${env.BUILD_USER}"
            }
        }

BUILD_USER就是當前部署人,後面直接引用該變數即可

獲取當前時間

def start = new Date().format('yyyy-MM-dd HH:mm:ss')

對於本專案,有如下引數,branch、部署專案名、部署的伺服器ip

我們需要將這些資訊給提取到企業微信的訊息中:

jenkinsfile如下(敏感資訊已脫敏):

def git_auth = "XXXXXX-XXXX-XXXX-XXX-XXXXXXXXX"
def git_url = "[email protected]:XXXXX/XXXXXX-server.git"
node {
    def start = new Date().format('yyyy-MM-dd HH:mm:ss')
    def selectedProjectNames = "${project_name}".split(",")
    def selectedServers = "${publish_server}".split(",")
    stage('拉取程式碼') {
        checkout([$class: 'GitSCM', branches: [[name: "*/${branch}"]], extensions: [], userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_url}"]]])
    }
    stage('編譯,安裝公共子工程') {
        sh "mvn -f xxxxx-base-starter clean install -Dmaven.test.skip=true"
    }
    stage('編譯,打包微服務工程') {
        for(int i = 0 ; i < selectedProjectNames.length; i++){
            def projectInfo = selectedProjectNames[i];
            sh "mvn -f ${projectInfo} clean install -Dmaven.test.skip=true"
            for(int j = 0 ; j < selectedServers.length; j++){
                def selectedServer = selectedServers[j];
                sshPublisher(publishers: [sshPublisherDesc(configName: "${selectedServer}", transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: "sh /xxxxx/${branch}/xxxx-xxxxx-server.sh ${projectInfo} ${branch}", execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: "/xxxxx/${branch}", remoteDirectorySDF: false, removePrefix: "${projectInfo}/target", sourceFiles: "${projectInfo}/target/${projectInfo}-1.0-SNAPSHOT.jar")], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
            }
        }
    }
    stage('webhook') {
        wrap([$class: 'BuildUser']) {
            script {
                BUILD_USER = "${env.BUILD_USER}"
            }
        }
        def head = "\"構建${JOB_NAME}:#${env.BUILD_ID}<font color=\\\"info\\\">成功</font>,詳細資訊如下:"
        def s1 = ">部署分支:<font color=\\\"comment\\\">${branch}</font>"
        def s2 = ">部署服務:<font color=\\\"comment\\\">${project_name}</font>"
        def s3 = ">部署伺服器:<font color=\\\"comment\\\">${publish_server}</font>"
        def execTime = start+"   "+new Date().format('yyyy-MM-dd HH:mm:ss')
        def s4 = ">部署時間:<font color=\\\"comment\\\">${execTime}</font>"
        def s5 = ">部署人:<font color=\\\"comment\\\">${BUILD_USER}</font>"
        def msg = "${head}"+"\n"+ "${s1}"+"\n"+"${s2}"+"\n"+"${s3}"+"\n"+"${s4}"+"\n"+"${s5}\""
        echo "${msg}"
        def body = "{ \"msgtype\": \"markdown\", \"markdown\": { \"content\": ${msg} } }"
        echo "${body}"
        httpRequest contentType: 'APPLICATION_JSON_UTF8', httpMode: 'POST', requestBody: "${body}", responseHandle: 'NONE', url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxx-xxxxx-xxx-xxxxx-xxxxxxxxxxx', wrapAsMultipart: false
    }
}

最後webhook一步,會發送Post請求,到企業微信機器人的webhook中.

然後每次只要部署成功,企業微信機器人都會在群裡傳送訊息: