How to send mattermost notifications in Jenkins using groovy? - jenkins

Any pointers on sending mattermost notifications using groovy in the Jenkinsfile? Is it similar to slacksend?

This worked for me:
mattermostSend(color: colorCode, icon: "https://jenkins.io/images/logos/jenkins/jenkins.png", message: message, channel: *channelname*, endpoint: *yourwebhookendpoint*)

Install the Mattermost Notification Plugin from Plugin Manager.
Scripts:
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
try {
mattermostSend (
color: "#2A42EE",
channel: 'Build_BOT',
endpoint: 'https://linktomattermost.com/hooks/yuwrgjeh38246239jkfh',
message: "Build STARTED: ${env.JOB_NAME} #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Link to build>)"
)
sh '''
mvn -B -DskipTests clean package
'''
} catch(e) {
currentBuild.result = "FAILURE"
} finally {
if(currentBuild.result == "FAILURE") {
mattermostSend (
color: "#e00707",
channel: 'Build_BOT',
endpoint: 'https://linktomattermost.com/hooks/yuwrgjeh38246239jkfh',
message: "Build FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Link to build>)"
)
} else {
mattermostSend (
color: "#00f514",
channel: 'Build_BOT',
endpoint: 'https://linktomattermost.com/hooks/yuwrgjeh38246239jkfh',
message: "Build SUCCESS: ${env.JOB_NAME} #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Link to build>)"
)
}
}
}
}
}
}
}

Related

Is there a conversations.setTopic for Slack Notification plugin

I've been looking at the slackSend function that's part of the Slack Notification plugin, however I was unable to find a way to change the topic of a channel. Is there a way to do this with Jenkins?
I tried the following on my JenkinsFile:
pipeline {
options {
disableConcurrentBuilds()
timestamps ()
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30'))
timeout(time: 45, unit: 'MINUTES')
}
agent {
label "jenkins-slave"
}
libraries {
lib('shared-lib')
}
stages {
stage('Deploy stage') {
steps {
script {
slackSend (
message: "A simple test topic",
channel: "xxxxxxxxx",
color: "#00FF00",
method: "conversations.setTopic",
topic: "Build succeeded!",
tokenCredentialId: "xxxxxxxxxx")
sh 'echo'
sh """
curl --request GET --url 'https://api.pagerduty.com/schedules/xxxxxx/users?since=2022-12-25T22:00:06-0500&until=2022-12-26T22:00:06-0500' --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Authorization: Token token=xxxxxxxx' --header 'Content-Type: application/json'| jq '.users[].name'
"""
}
}
}
}
I've also tried:
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
post {
success {
slackSend color: '#36a64f', message: "Build succeeded!", method: "conversations.setTopic", channel: "YOUR_CHANNEL_ID", topic: "Build succeeded!"
}
}
}
And also this
pipeline {
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
post {
success {
slackSend method: "conversations.setTopic", channel: "YOUR_CHANNEL_ID", topic: "Build succeeded!", color: '#36a64f', message: "Build succeeded!"
}
}
}
I am unsure if this function exists. Could someone let me know if there is a way to change topics on a slack channel within a JenkinsFile?
I never used slack plugin, but you can solve this by using there API directly to change the topic conversations.setTopic
and use curl to send the request in the pipeline

Jenkins won't run my build script from perforce

I have a build script I created which is located in a perforce streams depot at //HVS/Main/BuildScripts/hvs_client.jenkinsfile. However, when I run it it's just automatically successful. You can see in the image what it's doing.
I have set the Script Path to the correct location:
And I also have it setup with the correct stream path:
This exact setup works just fine on my windows server running jenkins. The only difference is that I'm trying to migrate my jenkins setup off of a physical machine and onto the cloud. The new master which is running on Ubuntu 20.04 is what is having these issues. I also have one "Node" which is a windows server which has the java agent installed and connected.
This is what my pipeline script looks like:
def channelId = 'removed_for_stackoverflow'
def threadId
def slackResponse
pipeline {
agent {label 'Windows'}
parameters {
choice(name: "BuildType", choices: ['Development', 'Shipping', 'Testing'], description: "What environment are you building to? Default is Development.")
string(name: "SevenZIPDir", defaultValue: "C:\\Program Files\\7-Zip\\7z.exe", description: "Location of 7zip executable.")
booleanParam(name: "clean", description: "Should jenkins clean the workspace?", defaultValue: false)
}
options {
skipDefaultCheckout()
}
stages {
stage('P4 Sync') {
steps {
script {
if (params.clean)
{
cleanWs()
}
p4sync charset: 'none', credential: '5feaca76-6a4a-4540-8a1e-e86ac8b3dc5b', populate: syncOnly(force: false, have: true, modtime: false, parallel: [enable: false, minbytes: '1024', minfiles: '1', threads: '4'], pin: '', quiet: true, revert: false), source: streamSource('//HVS/Main')
}
}
}
// https://github.com/jenkinsci/slack-plugin#bot-user-mode
// https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/ProgrammingWithCPP/UnrealArchitecture/VersioningAssetsAndPackages/
// https://www.perforce.com/manuals/jenkins/Content/P4Jenkins/variable-expansion.html
stage('Notify Slack users') {
steps {
script {
slackResponse = slackSend(channel: channelId, replyBroadcast: true, message: "Beginning build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} ${env.BUILD_URL}")
threadId = slackResponse.threadId
slackResponse.addReaction("stopwatch")
}
}
}
stage('Build Client') {
steps {
retry(3) {
bat("%WORKSPACE%/Engine/Build/BatchFiles/RunUAT.bat BuildCookRun -project=\"%WORKSPACE%/HVS/HVS.uproject\" -noP4 -platform=Win64 -clientconfig=Development -cook -allmaps -clean -build -stage -pak -CrashReporter -archive -archivedirectory=\"%WORKSPACE%/temp/Development/x64\"")
}
}
}
/*stage('Deploy to Steam') {
}*/
stage('Archive Artifacts'){
steps {
dir("temp/${params.BuildType}/x64/WindowsNoEditor") {
bat "\"${params.SevenZIPDir}\" a -mx=1 -mmt=on %WORKSPACE%/temp/HVS_${params.BuildType}_x64_${P4_CHANGELIST}.7z *"
}
archiveArtifacts artifacts: "temp/*.7z", followSymlinks: false, onlyIfSuccessful: true
}
}
}
post {
success {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} successful! ${env.BUILD_URL}")
slackResponse.addReaction("white_check_mark")
}
}
failure {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} failed! ${env.BUILD_URL}")
slackResponse.addReaction("red_circle")
}
}
unstable {
script {
slackSend(channel: threadId, replyBroadcast: true, message: "Build of ${env.JOB_NAME} for CL#${P4_CHANGELIST} is not stable #channel ${env.BUILD_URL}")
slackResponse.addReaction("warning")
}
}
}
}
Has anyone seen this before? My one "Node" also has the label "Windows"
I didn't have the Pipeline plugin installd for some reason. It works now.

jenkins pipeline updateGitlabCommitStatus not working

GITLAB_VERSION: GitLab Enterprise Edition 13.9.3-ee
JENKINS_VERSION: 2.263.4
I have crated a jenkins pipeline which is being triggered by change in gitlab, but its not updating gitlab status.
pipeline {
agent any
stages {
stage('cloning from gitlab'){
steps{
git credentialsId: '7d13ef14-ee65-497b-8fba-7519f5012e81', url: 'git#git.MYDOMAIN.com:root/popoq.git'
}
}
stage('build') {
steps {
echo 'Notify GitLab'
updateGitlabCommitStatus name: 'Jenkins-build', state: 'pending'
echo 'build step goes here'
}
}
stage('echoing') {
steps{
echo "bla blaa bla"
}
}
stage(test) {
steps {
echo 'Notify GitLab'
echo 'test step goes here'
updateGitlabCommitStatus name: 'Jenkins-build', state: 'success'
}
}
}
}
its not showing any pipline in gitlab, any suggestions?
I think you miss a "gitlabBuilds" command in an "option" block declaring the steps you will have in your build.
options {
gitLabConnection('xxx-gitlab')
gitlabBuilds(builds: ['step1', 'step2', 'step3'])
}
Then you can reference those steps with the "updateGitlabCommitStatus" but you'd better use the "gitlabCommitStatus" command like this:
pipeline {
agent any
options {
gitLabConnection('xxx-gitlab')
gitlabBuilds(builds: ['step1', 'step2', 'step3'])
}
stages {
stage('step1'){
steps{
gitlabCommitStatus(name:'step1') {
git credentialsId: '7d13ef14-e', url: 'xxxxxxx'
}
} // end steps
} // end stage
stage('step2'){
steps{
gitlabCommitStatus(name:'step2') {
.......
}
} // end steps
} // end stage
}
pipeline {
agent {
label 'agent_gradle'
}
options {
gitLabConnection('Gitlab Jenkins integration API connection test')
gitlabBuilds(builds: ['step1', 'step2'])
}
stages {
stage('Build') {
steps {
gitlabCommitStatus(name: 'step1') {
container(name: 'gradle') {
echo 'Building the application...'
}
}
}
}
stage('Test') {
steps {
gitlabCommitStatus(name: 'step2') {
container(name: 'gradle') {
echo 'Testing the application...'
}
}
}
}
}
}

Is there a way to show the name of failed tests in email body via jenkins

I want to see the names of all failed tests in email body when an email is triggered by jenkins using editable email notification plugin.
I am using TestNg with selenium+java.
You can add allure reports in your tests and send the allure links or file via emial as in code below:
stage('Create properties file for allure') {
steps {
sh '''
export CHATBOT_ENV
touch allure-results/environment.properties
'''
}
}
stage('Allure reports') {
steps {
script {
allure([
includeProperties: true,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: 'allure-results/']]
])
}
}
}
}
post
{
always
{
echo 'This will always run'
emailext body: "Build URL: ${BUILD_URL}",
attachmentsPattern: "**/path_to_your_report",
subject: "$currentBuild.currentResult-$JOB_NAME",
to: 'nobody#optum.com'
}
}
}
THe build URL can be used to navigate to allure report.

go: not found in declarative Jenkinsfile

I have Jenkins running on Docker and I have the following Jenkinsfile on github
node {
def root = tool name: 'Go 1.12.6', type: 'go'
ws("${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_ID}/src/github.com/project/repo") {
withEnv(["GOROOT=${root}", "GOPATH=${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_ID}/", "PATH+GO=${root}/bin"]) {
env.PATH="${GOPATH}/bin:$PATH"
stage('Clone repository') {
checkout scm
}
stage('Test repo') {
sh 'go test -v'
}
stage('Build image') {
app = docker.build("docker/repo")
}
stage('Push image') { */
docker.withRegistry('https://registry.hub.docker.com', 'docker-hub-credentials') {
app.push("${env.BUILD_NUMBER}")
app.push("latest")
}
}
}
}
}
But no matter what I try I get the following error:
+ go version
/var/jenkins_home/jobs/repo/builds/45/src/github.com/project/repo#tmp/durable-00e72894/script.sh: line 1: go: not found
Jenkins reboots might just fix it

Resources