Jenkinsfile里定義對象和函數,獲取git提交人, 發送釘釘通知

  • 2020 年 3 月 27 日
  • 筆記

自從開始使用Jenkinsfile作為Jenkins配置後就一發不可收,因為開發者自定義CI腳本實在太方便了。

比如,最近開發的以一個項目涉及多人,提交衝突挺多的,有的人自己沒編譯通過就提交了,導致後面的人被阻塞,所以我們需要告訴他: 提交失敗了。

首先,Jenkinsfile應該怎麼用呢, 參見: https://www.cnblogs.com/woshimrf/p/gitlab-with-jenkins.html

定義Jenkinsfile的時候想要釘釘通知,首先獲取git提交人:

最外層:    class MyChange {     String author;     String msg;  }  @NonCPS  def getChanges()  {      def changeLogSets = currentBuild.changeSets      for (int i = 0; i < changeLogSets.size(); i++)      {          def entries = changeLogSets[0].items          for (int j = 0; j < entries.length; j++)          {              def entry = entries[0]              def change = new MyChange()              change.author = entry.author              change.msg = entry.msg              return change          }      }    }    然後在node節點裡定義變數    ding_group_access_token = "c20d35654da77a99d8869e04xxxxxxxd1a81aasssa2"  ding_jenkinsUrl = "http://jenkins.ryan.com/view/我的view名稱/"    最後在失敗的時候通知:      stage('Compile And UnitTest') {      echo "2.Compile the code"      try {          sh "mvn clean install"      } catch (Exception ex) {          updateGitlabCommitStatus name: 'build', state: 'failed'          def change = getChanges()          dingTalk accessToken: "${ding_group_access_token}", imageUrl: '', jenkinsUrl: "${ding_jenkinsUrl}", message: "@所有人 構建失敗@$change.author $change.msg" , notifyPeople: "$change.author"          throw ex;      } finally {        }        updateGitlabCommitStatus name: 'build', state: 'success'  }

最終Jenkinsfile可能是這個樣子的

文件位置  my-project  - .deploy     - Jenkinsfile  - src

在jenkins里創建pipeline job, 並指定Jenkinsfile

Jenkinsfile

class MyChange {     String author;     String msg;  }  @NonCPS  def getChanges()  {      def changeLogSets = currentBuild.changeSets      for (int i = 0; i < changeLogSets.size(); i++)      {          def entries = changeLogSets[0].items          for (int j = 0; j < entries.length; j++)          {              def entry = entries[0]              def change = new MyChange()              change.author = entry.author              change.msg = entry.msg              return change          }      }    }    node {      properties([gitLabConnection('gitlab-bigdata')])        stage('Prepare') {          echo "1.Prepare Stage"          checkout scm          updateGitlabCommitStatus name: 'build', state: 'pending'          mvn_module = '多模組項目mvn子模組'          pom = readMavenPom file: "${mvn_module}/pom.xml"          k8s_label = "項目在k8s集群中的名稱"          docker_host = "自己的docker私服"          ding_group_access_token = "c20d35654da77a99d8869e041xxxac7d6699xxxxxx"          ding_jenkinsUrl = "http://jenkins.ryan.com/view/job所在的view/"          //要部署的k8s集群, 默認是杭州(config-hangzhou), 可選上海(config-shanghai)          k8s_cluster_node = "config-hangzhou"          //部署環境          profile=""          if(env.BRANCH_NAME == 'dev') {              profile = "dev"              k8s_cluster_node = "config-dev"          }          if(env.BRANCH_NAME == 'test') {              profile = "test"              k8s_cluster_node = "config-shanghai"          }          if(env.BRANCH_NAME == 'master') {              profile = "prod"              k8s_cluster_node = "config-hangzhou"          }            img_name = "${pom.groupId}-${pom.artifactId}"          docker_img_name = "${docker_host}/${img_name}"          echo "group: ${pom.groupId}, artifactId: ${pom.artifactId}, version: ${pom.version}"          echo "docker-img-name: ${docker_img_name}"          script {              build_tag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()              build_tag = "${env.BRANCH_NAME}-${build_tag}"                currentBuild.displayName = BUILD_NUMBER + "_" +build_tag          }      }        stage('Compile And UnitTest') {          echo "2.Compile the code"          try {              sh "mvn clean install"          } catch (Exception ex) {              updateGitlabCommitStatus name: 'build', state: 'failed'              def change = getChanges()              dingTalk accessToken: "${ding_group_access_token}", imageUrl: '', jenkinsUrl: "${ding_jenkinsUrl}", message: "@所有人 構建失敗@$change.author $change.msg" , notifyPeople: "$change.author"              throw ex;          } finally {            }            updateGitlabCommitStatus name: 'build', state: 'success'      }            if (env.BRANCH_NAME == 'dev' ||env.BRANCH_NAME == 'test' || env.BRANCH_NAME == 'master') {          stage('Build Docker Image') {              echo "4.Build Docker Image Stage"              sh "docker build -t ${docker_img_name}:${build_tag} " +                      " --build-arg JAR_FILE=target/${mvn_module}.jar " +                      " --build-arg profile=${profile} " +                      " -f ${mvn_module}/.deploy/Dockerfile ./${mvn_module}"          }            stage('Push Docker Image') {              echo "5.Push Docker Image Stage"              //sh "mvn deploy -Dmaven.test.skip=true"              sh "docker tag ${docker_img_name}:${build_tag} ${docker_img_name}:latest"              sh "docker tag ${docker_img_name}:${build_tag} ${docker_img_name}:${pom.version}"              withCredentials([usernamePassword(credentialsId: 'docker-register-sz-shuwei', passwordVariable: 'dockerPassword', usernameVariable: 'dockerUser')]) {                  sh "docker login -u ${dockerUser} -p ${dockerPassword} ${docker_host}"                  sh "docker push ${docker_img_name}:latest"                  sh "docker push ${docker_img_name}:${pom.version}"                  sh "docker push ${docker_img_name}:${build_tag}"              }          }              stage("Deploy to k8s - ${profile}") {              echo "6. Deploy Stage"                updateGitlabCommitStatus name: 'deploy', state: 'pending'              sh "sed -i 's/<IMG_NAME>/${img_name}/g;s/<IMG_TAG>/${build_tag}/g;s/<k8s-label>/${k8s_label}/g' ${WORKSPACE}/${mvn_module}/.deploy/${profile}-k8s.yaml"              sh "kubectl --kubeconfig /home/jenkins/.kube/${k8s_cluster_node} " +                      "apply -f ${WORKSPACE}/${mvn_module}/.deploy/${profile}-k8s.yaml --record"              sh "sleep 5"              echo "創建的實例:"              sh "kubectl --kubeconfig /home/jenkins/.kube/${k8s_cluster_node}  get po -o wide | grep ${k8s_label}"              echo "您的應用svc: "              sh "kubectl --kubeconfig /home/jenkins/.kube/${k8s_cluster_node}  get svc | grep ${k8s_label}"                updateGitlabCommitStatus name: 'deploy', state: 'success'          }      }        }