Jenkins Pipline推送構建結果到飛書Robot

先上圖,效果如上圖

 

截至2022年7月,Jenkins插件中心上面都沒有飛書相關的插件,只有釘釘的插件,使用釘釘插件可以方便的將構建結果推送到釘釘羣,網上也沒找到相關推送到飛書羣的文章,只好參考釘釘推送相關代碼自行實現了。

 

在Pipline腳本中引用第三方庫

def larkmes = new org.devops.larkmes()

 

新建自定義共享庫,完整路徑爲

jenkinslibrary/src/org/devops/larkmes.groovy

 

內容如下:

package org.devops

def GetChangeString() {
    MAX_MSG_LEN = 100
    def changeString = ""
    def changeLogSets = currentBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            truncated_msg = entry.msg.take(MAX_MSG_LEN)
            commitTime = new Date(entry.timestamp).format("yyyy-MM-dd HH:mm:ss")
            changeString += "·${truncated_msg} [${entry.author} ${commitTime}]\\n"
        }
    }
    if (!changeString) {
        changeString = "No new changes"
    }
    return changeString
}

def request_post(endpoint, comment) {
    println(comment)
    def url = new URL(endpoint)
    def url_connection = url.openConnection()

    url_connection.setRequestMethod("POST")
    url_connection.setDoOutput(true)
    url_connection.setRequestProperty("Content-Type", "application/json")

    url_connection.getOutputStream().write(comment.getBytes("UTF-8"))

    def response_code = url_connection.getResponseCode()
    println(response_code)
    if (response_code != 200) {
        println("Warning: faled to post message")
    }
    else {
        println("successed to post message")
    }
}

def GetSuccessContent()
{
  wrap([$class: 'BuildUser']) {
    def Content = ""
	  Content = "項目名稱:**${env.JOB_NAME}**\\n當前版本:**${env.BUILD_NUMBER}**\\n構建發起:**${env.BUILD_USER}**\\n持續時間:**${currentBuild.durationString}**\\n構建日誌:**[點擊查看詳情](${env.BUILD_URL}console)**\\n構建結果:**構建成功 ✅**"
    return Content
	} 
}

def GetFailureContent()
{
  wrap([$class: 'BuildUser']) {
    def Content = ""
	  Content = "項目名稱:**${env.JOB_NAME}**\\n當前版本:**${env.BUILD_NUMBER}**\\n構建發起:**${env.BUILD_USER}**\\n持續時間:**${currentBuild.durationString}**\\n構建日誌:**[點擊查看詳情](${env.BUILD_URL}console)**\\n構建結果:**構建失敗 ❌**"
    return Content
	} 
}

def GetMsgData(content, color) {
  def msg_data = """
  {
    "msg_type":"interactive",
    "card":{
      "config":{
        "wide_screen_mode": true,
        "enable_forward": true
      },
      "elements":[
        {
          "tag": "div",
          "text": {
            "content": "${content}",
            "tag": "lark_md"
          }
        },
        {
          "tag": "hr"
        },
        {
          "tag": "div",
          "text": {
            "content": "更新記錄:\\n${GetChangeString()}",
            "tag": "lark_md"
          }
        }
      ],
      "header":{
        "template": "${color}",
        "title":{
          "content": "Jenkins構建報告",
          "tag": "plain_text"
        }
      }
    }
  }
  """
	
  return msg_data
}

def SuccessNotice(wehook) {
  def content = GetSuccessContent()
  def msg_data = GetMsgData(content, "green")
  request_post(wehook, msg_data)   
}

def FailureNotice(wehook) {
  def content = GetFailureContent()
  def msg_data = GetMsgData(content, "red")
  request_post(wehook, msg_data)
}

 

在Pipline中這樣調用:

def larkmes = new org.devops.larkmes()

pipeline {
    agent any
    stages {
        stage('Test False') {
            steps {
                sh """
                    false
                """
            }
        }
    }
    post {
        success {
            script {
                larkmes.SuccessNotice("${env.LARK_WEHOOK}")
            }
        }
        failure {
            script {
                larkmes.FailureNotice("${env.LARK_WEHOOK}")
            }
        }
    }
}

建議在Jenkins中自定義全局變量,Pipline從Jenkins變量中讀取wehook地址,這樣就不用在每個Pipline中配置wehook地址了

參考鏈接:
https://www.ssgeek.com/post/jenkinssharelibrary-shi-jian-zhi-zi-ding-yi-tong-zhi-qi/
https://blog.csdn.net/weixin_42170236/article/details/121907647

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章