Jenkins Pipeline 配置企业微信通知(try-catch捕获build failed)
文章目錄
- 1 消息推送代碼及實現原理
- 2 try-catch捕獲build failed
目前 Jenkins 有自帶的 qy-wechat-notification-plugin這個插件可以直接配置企業微信機器人的 Webhook 地址,即可實現build之后進行企業微信通知的功能。但是這個插件只能在 Freestyle project 等帶有 Post build action 的Project中調用,如下圖:
若 Project 為 Pipeline ,那么是無法直接調用此插件,原因是Pipeline中沒有Post-build Actions這個參數,如下圖:
為了解決這個問題,搜索了好多資料,最后找到了一篇文章,參考文章如下,稍加修改即可實現try-catch捕獲build failed
持續集成之企業微信通知:5:在Jenkins中向企業微信推送消息
下邊開始詳細說下
1 消息推送代碼及實現原理
send_message.sh
#!/bin/sh # 此腳本可實現jenkins往企業微信和釘釘推送消息usage(){echo "usage: $0 TYPE TITLE CONTENT [URL]"echo " TYPE: wechat|dingtalk" }TYPE="$1" TITLE="$2" CONTENT="$3" URL="$4"CHAT_CONTENT_TYPE='Content-Type: application/json' DEFAULT_PIC_URL="https://img-blog.csdnimg.cn/20191227152859635.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9saXVtaWFvY24uYmxvZy5jc2RuLm5ldA==,size_16,color_FFFFFF,t_70" DINGTALK_DEFAULT_WORDS=" [LiuMiaoMsg]" if [ $# -lt 3 ]; thenusageexit 1 fiif [ _"${TYPE}" = _"wechat" ]; thenCHAT_WEBHOOK_URL='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key' elif [ _"${TYPE}" = _"dingtalk" ]; thenCHAT_WEBHOOK_URL='https://oapi.dingtalk.com/robot/send?access_token' elseusageexit 1 fiif [ _"${CHAT_WEBHOOK_KEY}" = _"" ]; thenecho "please make sure CHAT_WEBHOOK_KEY has been exported as environment variable"usageexit 1 fiif [ _"${URL}" = _"" ]; thenURL="https://blog.csdn.net/Mr_rsq/article/details/110956983" fiecho "## send message for : ${TYPE}" if [ _"${TYPE}" = _"wechat" ]; thencurl "${CHAT_WEBHOOK_URL}=${CHAT_WEBHOOK_KEY}" \-H "${CHAT_CONTENT_TYPE}" \-d '{"msgtype": "news","news": {"articles" : [{"title" : "'"${TITLE}"'","description" : "'"${CONTENT}"'","url" : "'"${URL}"'","picurl" : "'"${DEFAULT_PIC_URL}"'"}]}}' elif [ _"${TYPE}" = _"dingtalk" ]; thencurl "${CHAT_WEBHOOK_URL}=${CHAT_WEBHOOK_KEY}" \-H "${CHAT_CONTENT_TYPE}" \-d '{"msgtype": "link", "link": {"text": "'"${CONTENT}${DINGTALK_DEFAULT_WORDS}"'", "title": "'"${TITLE}"'", "picUrl": "'"${DEFAULT_PIC_URL}"'", "messageUrl": "'"${URL}"'"}}' elseusageexit 1 fi實現原理:
其實原理很簡單,就是通過使用curl命令的-d和-H參數去模擬json格式的post請求,通過往send_message.sh腳本中傳入title和picUrl等參數,從而實現企業微信通知的功能。
腳本使用:
(1)在使用send_message腳本之前需要先配置CHAT_WEBHOOK_KEY
(2)然后直接執行腳本
bash send_message.sh wechat "rsq_test" "This is a test messages."(3)企業微信中查看:
2 try-catch捕獲build failed
我這邊使用的的腳本化pipeline而不是聲明式pipeline,為了配置好也費了一番功夫,搜索了一大堆資料。
代碼如下:
通過Jenkins的內置變量,最后可以直接推送build failed的Job_url,執行如下命令
bash send_message.sh wechat "Ubuntu %JOB_NAME% build failed." "URL: %BUILD_URL%" "%BUILD_URL%"Jenkins內置變量
PS:try-catch支持的命令(略多)
acceptGitLabMR, addGitLabMRComment, archive, bat, build, catchError, checkout, container, containerLog, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, findBuildScans, getContext, git, gitlabBuilds, gitlabCommitStatus, httpRequest, input, isUnix, junit, library, libraryResource, load, lock, mail, milestone, node, p4, p4approve, p4publish, p4sync, p4tag, p4unshelve, parallel, podTemplate, powershell, properties, publishHTML, pwd, pwsh, readFile, readTrusted, resolveScm, retry, script, sh, sleep, stage, stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstable, unstash, updateGitlabCommitStatus, validateDeclarativePipeline, waitUntil, warnError, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws] or symbols [all, allOf, allure, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, approve, architecture, archiveArtifacts, artifactManager, attach, authorizationMatrix, autoClean, batchFile, bitbucket, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDescription, buildDiscarder, buildName, buildTimestamp, buildTimestampExtraProperties, buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs, cleanup, clientSpec, clock, cloud, command, configMapVolume, containerEnvVar, containerLivenessProbe, containerTemplate, credentials, cron, crumb, culprits, default, defaultView, demand, depotSource, developers, disableConcurrentBuilds, disableResume, docker, dockerCert, dockerfile, downloadSettings, downstream, dumb, durabilityHint, dynamicPVC, emptyDirVolume, emptyDirWorkspaceVolume, envVar, envVars, environment, equals, expression, file, fileParam, filePath, fingerprint, fishEye, flushOnly, forceClean, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, gitBranchDiscovery, gitHubBranchDiscovery, gitHubBranchHeadAuthority, gitHubForkDiscovery, gitHubSshCheckout, gitHubTagDiscovery, gitHubTrustContributors, gitHubTrustEveryone, gitHubTrustNobody, gitHubTrustPermissions, gitLabConnection, gitTagDiscovery, github, githubPush, gitlab, globalLib, gradle, graphClean, graphSource, headRegexFilter, headWildcardFilter, hostPathVolume, hostPathWorkspaceVolume, hyperlink, hyperlinkToModels, incremental, inheriting, inheritingGlobal, installSource, isRestartedRun, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, kubernetes, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, manualSpec, masterBuild, matrix, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, merge, modernSCM, multiBranch, multiGraph, multiStreams, multiSwarm, myView, never, newContainerPerStage, nfsVolume, nfsWorkspaceVolume, node, nodeProperties, nonInheriting, none, not, note, onFailure, openGrok, override, overrideIndexTriggers, p4Trigger, p4Web, p4cleanup, p4groovy, p4sync, paneStatus, parallel, parallelsAlwaysFailFast, parameterizedCron, parameters, password, pathFilter, pattern, perforce, permanent, persistentVolumeClaim, persistentVolumeClaimWorkspaceVolume, pipeline-model, pipelineTriggers, plainText, plugin, podAnnotation, podEnvVar, podLabel, pollSCM, portMapping, preserveStashes, previewOnly, projectNamingStrategy, proxy, publish, queueItemAuthenticator, quietPeriod, qyWechatNotification, rateLimitBuilds, recipients, requestor, run, runParam, sSHLauncher, schedule, scmRetryCount, scriptApproval, scriptApprovalLink, search, secretEnvVar, secretVolume, security, shell, shelve, skipDefaultCheckout, skipStagesAfterUnstable, slave, sourceRegexFilter, sourceWildcardFilter, specFileSpec, ssh, sshUserPrivateKey, stackTrace, standard, staticSpec, status, streamSource, streamSpec, string, stringParam, submit, swapSpace, swarm, syncOnly, tag, templateSource, templateSpec, text, textParam, ticket, ticketMode, tmpSpace, toolLocation, triggeredBy, trust, unsecured, unshelve, upstream, upstreamDevelopers, user, userFilter, userSeed, usernameColonPassword, usernamePassword, viewFilter, viewPattern, viewsTabBar, weather, withAnt, zfs, zip] or globals [currentBuild, docker, env, params, pipeline, scm]總結
以上是生活随笔為你收集整理的Jenkins Pipeline 配置企业微信通知(try-catch捕获build failed)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win7电脑恢复系统设置或计算机点不了,
- 下一篇: 研究生生涯实习记录