Is there a conversations.setTopic for Slack Notification plugin - jenkins

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

Related

How to add error handling code to `catchError()` in Jenkins?

If I have a pipeline where individual stages are allowed to fail, without failing the whole job, how can I add error handling to, for instance, send an email to an admin, when that stage fails? I've tried using post failure, but it doesn't work.
pipeline {
agent any
stages {
stage('1') {
steps {
sh 'exit 0'
}
}
stage('2') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
sh "exit 1"
}
}
post {
failure {
echo 'Sending email to admin...'
}
}
}
stage('3') {
steps {
sh 'exit 0'
}
}
}
}
I got this question in a comment and thought it was worth asking and answering as a proper question.
Unfortunately, for now, I think the only way is to use try catch in a script block and re-throw the error after performing the error handling. See example below:
pipeline {
agent any
stages {
stage('1') {
steps {
sh 'exit 0'
}
}
stage('2') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
script {
try {
sh "exit 1"
} catch (e) {
echo 'send email'
throw e
}
}
}
}
}
stage('3') {
steps {
sh 'exit 0'
}
}
}
}

Jenkins multipe post sections per stage

I have two question for usage of post section in Jenkins pipeline
1.Can we use multiple post section per stage in Jenkins declarative Pipeline?
2.Can we run sh command in post section?
pipeline{
stages{
stage("....") {
steps {
script {
....
}
}
post {
failure{
sh "....."
}
}
stage("Second stage") {
when {
expression { /*condition */ }
}
steps {
script{
....
}
post {
always {
script {
sh "..."
}
}
}
}
}
You can find information in https://jenkins.io/doc/book/pipeline/syntax/#post
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
post {
success {
sh label: 'success', script: 'ls'
}
failure {
sh label: 'failure', script: 'ls'
}
aborted {
sh label: 'aborted', script: 'ls'
}
}
}
You can use Post steps each Stage, but pipeline will stop on first failure. In example below, if Stage 1 fail Stage 2 will be skipped. Post after all stages will always executed.
pipeline{
stages{
stage("Stage 1") {
steps {
catchError(message: 'catch failure') {
script {
sh "echo stage 1"
}
}
}
post {
always {
sh "echo post stage 1"
}
}
}
stage("Stage 2") {
when {
expression { /*condition */ }
}
steps {
script{
sh "echo stage 2"
}
}
post {
always {
script {
sh "echo post stage 2"
}
}
}
}
}
post {
always {
sh "echo post after all stages"
}
}
}

How to populate Jenkins build parameter values from URL in Jenkins declarative pipeline

How can I populate choice parameter from the URL?
I'm able to download and save values inside environment variable but if I try to use it I get error:
if I replace choicesFoo with choicesURL in parameters section, I get error.
Here is my pipeline:
def choicesFoo = ['x','y']
pipeline{
agent {
node {
label 'LinuxOpt'
}
}
environment{
choicesUrl = sh(script: "curl http://example.com/foo.txt", returnStdout: true)
}
parameters {
choice(name: 'CHOICE', choices: choicesFoo, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}
You can try preparing your choices before declaring a pipeline, e.g. like this:
def choicesUrl
node('Prepare Choices') {
stage('Get Choices') {
choicesUrl = sh(
script: "curl http://example.com/foo.txt",
returnStdout: true).trim()
}
}
pipeline{
agent { node { label 'LinuxOpt' } }
parameters {
choice(name: 'CHOICE', choices: choicesUrl, description: 'Pick an option')
}
stages {
stage('Build') {
steps {
sh 'echo run build'
sh "echo ${choicesUrl}"
}
}
}
}

How to send mattermost notifications in Jenkins using groovy?

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>)"
)
}
}
}
}
}
}
}

How can I use post step in Jenkins pipeline with kubernetes plugin

I try to use the post steps with the Jenkins kubernetes plugin. Does anyone has an idea?
java.lang.NoSuchMethodError: No such DSL method 'post' found among steps
My pipeline:
podTemplate(
label: 'jenkins-pipeline',
cloud: 'minikube',
volumes: [
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
]) {
node('jenkins-pipeline') {
stage('test') {
container('maven') {
println 'do some testing stuff'
}
}
post {
always {
println "test"
}
}
}
}
As of this writing, Post is only supported in declarative pipelines.
You could have a look at their declarative example if you absolutely must use post.
pipeline {
agent {
kubernetes {
//cloud 'kubernetes'
label 'mypod'
containerTemplate {
name 'maven'
image 'maven:3.3.9-jdk-8-alpine'
ttyEnabled true
command 'cat'
}
}
}
stages {
stage('Run maven') {
steps {
container('maven') {
sh 'mvn -version'
}
}
}
}
}
This example shows how to use the post step using the Kubernetes plugin:
pipeline {
agent {
kubernetes {
label "my-test-pipeline-${BUILD_NUMBER}"
containerTemplate {
name "my-container"
image "alpine:3.15.0"
command "sleep"
args "99d"
}
}
}
stages {
stage('Stage 1') {
steps {
container('my-container') {
sh '''
set -e
echo "Hello world!"
sleep 10
echo "I waited"
echo "forcing a fail"
exit 1
'''
}
}
}
}
post {
unsuccessful {
container('my-container') {
sh '''
set +e
echo "Cleaning up stuff here"
'''
}
}
}
}

Resources