11

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?

6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.