如何在管道中的函数中获取全局变量的值?

how can I get the value of a global variable within a function in a pipeline?

我有一个包含几个步骤的声明式管道。最后,我向 slack 发送了一条消息,其中包含编译时间的一些统计信息和更多信息。我想发送以防它在失败的阶段失败。我已经设置了一个全局变量,但函数似乎无法读取它的值。这是我所拥有的简化版本:

def FAILED_STAGE

def sendSlackNotifcation() 
{
    if ( currentBuild.currentResult == "SUCCESS" ) {
        slackSend message: "${currentBuild.result}", channel: '#jenkins_bot2'
    }
        
    else {
        slackSend color : "#FF0000", message: "${FAILED_STAGE}", channel: '#jenkins_bot2'

    }
}

pipeline {
    agent any

    stages {
        stage('stage1') {
            steps{
                echo "stage1"
            }
        }     
        
        stage('stage2') {
            steps{
                echo "stage2"
            }
        }
        
        stage("Stage 3") {
            steps {
                script {
                    FAILED_STAGE=env.STAGE_NAME
                    echo "${FAILED_STAGE}"
                    error "failed for some reason."
                }
            }
        }
    }
    post {
    failure {
        sendSlackNotifcation()
        }
    }

}

这是我得到的输出:

13:38:53  [Pipeline] {
13:38:53  [Pipeline] stage
13:38:53  [Pipeline] { (stage1)
13:38:53  [Pipeline] echo
13:38:53  stage1
13:38:53  [Pipeline] }
13:38:53  [Pipeline] // stage
13:38:53  [Pipeline] stage
13:38:53  [Pipeline] { (stage2)
13:38:53  [Pipeline] echo
13:38:53  stage2
13:38:53  [Pipeline] }
13:38:53  [Pipeline] // stage
13:38:53  [Pipeline] stage
13:38:53  [Pipeline] { (Stage 3)
13:38:53  [Pipeline] script
13:38:53  [Pipeline] {
13:38:53  [Pipeline] echo
13:38:53  Stage 3
13:38:53  [Pipeline] error
13:38:53  [Pipeline] }
13:38:53  [Pipeline] // script
13:38:53  [Pipeline] }
13:38:53  [Pipeline] // stage
13:38:53  [Pipeline] stage
13:38:53  [Pipeline] { (Declarative: Post Actions)
13:38:53  Error when executing failure post condition:
13:38:53  groovy.lang.MissingPropertyException: No such property: FAILED_STAGE for class: WorkflowScript

它会起作用,如果你这样做的话

def failIn
def printStatus(def msg) {
    echo "msg : ${msg}"
}
pipeline {
    agent any;
    stages {
        stage("01") {
            steps {
                script {
                    failIn=env.STAGE_NAME    
                }
            }
        }
    }
    post {
        always {
            printStatus(failIn)
        }
    }
}