HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Jenkins Pipeline job; proper quoting for slackSend step

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
quotingslacksendjenkinsstepforproperjobpipeline

Problem

This is probably 100% user error, but I can't get a pipeline job to use a variable as the channel name in a slackSend step.

This uses both the Slack plugin and the Build User Vars Plugin. I'm trying to use BUILD_USER_FIRST_NAME to identify which channel to Slack back to (ie, the one starting the build should be the one to get the message).

Got halfway there with this article on how to use the build user plugin in a pipeline job, but substituting the variable is tripping me up.

The relevant part of the job looks like this;

stage ('message') {

    wrap([$class: 'BuildUser']) {

        sh "printf '%s' ${BUILD_USER_FIRST_NAME} > name.txt"

    }

    archiveArtifacts artifacts: 'name.txt'
    name = readFile('name.txt')
    echo "name is $name" //works fine, I get Alex

    if ( "$output" != null ) {
        slackSend (channel: '@$name', color: '#36A64F', message: "Job succeeded")
    } else {
        slackSend (channel: '@$name', color: '#36A64F', message: "Job failed")
    }

}


I've tried the following in place of the channel bit, all have failed with indeterminate Slack post may have failed. Response: Invalid channel specified errors.

channel: '@${name}',
channel: '@" + ${name} + "',
channel: '@"${name}"',


Expected output is that it would resolve to channel: '@Alex',

What's the proper syntax?

Solution

In Groovy you have to use double quotes to get string interpolation:

if ( "$output" != null ) {
        slackSend (channel: "@${name}", color: '#36A64F', message: "Job succeeded")
    } else {
        slackSend (channel: "@${name}", color: '#36A64F', message: "Job failed")
    }


You can also probably do something like this to avoid it entirely and have less duplication:

name = '@' + readFile('name.txt')

slackSend (channel: name //etc.

Code Snippets

if ( "$output" != null ) {
        slackSend (channel: "@${name}", color: '#36A64F', message: "Job succeeded")
    } else {
        slackSend (channel: "@${name}", color: '#36A64F', message: "Job failed")
    }
name = '@' + readFile('name.txt')

slackSend (channel: name //etc.

Context

StackExchange DevOps Q#1121, answer score: 6

Revisions (0)

No revisions yet.