Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

cannot use env variable in groovy script outside of jenkins pipeline


Team, ${env.test_USR} unable to use it outside of pipeline

I am able to set and use the variable inside pipeline but the same var is not working when sending slackNotify. for slack message am getting null that means env var was not found or read. any hint how to define env var outside pipeline so that slack can use it?

it works for gerritCheck and i get the id but var is not getting set for slackNotify call.

error output

https://sonar.company.com/dashboard?id=null
`

expected

https://sonar.company.com/dashboard?id=test_12345
notifyChannel = "#sw-test"

sonarStageLink = "SonarQube: <https://sonar.company.com/dashboard?id=${env.test_USR}>"


def slackNotify(String status, String color) {
    slackSend (
        channel: notifyChannel,
        color: color,
        message: "Analysis: \n${sonarStageLink}\n"
    )
}


pipeline {
    agent {
        label 'test'
    }

    environment {
        RUN_SONAR_URL = 'https://sonar.company.com'
        test = credentials('test-pullbranchanalysis')
    post {
        success {
            gerritCheck checks: ['jenkins:code-analysis': 'SUCCESSFUL'], url: "id=${env.test_USR}"
            script {
                if (!params.Refresh) {
                    echo "success"
                    slackNotify("succeeded", "good")

Solution

  • This is likely an issue with the positioning of the variable. If you were to move the sonarStageLink variable in to the pipeline as an env variable, this should start working:

    def slackNotify() {
        echo sonarStageLink
    }
    
    pipeline {
        agent any
        environment {
            test_USR = "TEST"
            sonarStageLink = "SonarQube: <https://sonar.company.com/dashboard?id=${env.test_USR}>"
        }
        stages {
            stage('Hello') {
                steps {
                    echo 'Hello'
                }
            }
        }
        post {
            success {
                script {
                    slackNotify()
                }
            }
        }
    }
    

    Results:

    SonarQube: https://sonar.company.com/dashboard?id=TEST