在脚本块的 Jenkinsfile 中使用 def 和不使用 def 有什么区别?

Ale*_*lex 0 pipeline jenkins jenkins-pipeline

我有两个 Jenkinsfile 作为示例: A_Jenkinsfile 的内容是:

pipeline {
    agent any
    stages {
        stage("first") {
            steps {
                script {
                 foo = "bar"
                }
            sh "echo ${foo}"
            }
        }
        stage("two") {
            steps {
            sh "echo ${foo}"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外一个是B_Jenkinsfile,其内容是:

pipeline {
    agent any
    stages {
        stage("first") {
            steps {
                script {
                 def foo = "bar"
                }
            sh "echo ${foo}"
            }
        }
        stage("two") {
            steps {
            sh "echo ${foo}"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我构建它们时,B_Jenkinsfile 失败,A_Jenkinsfile 成功。

在脚本块的 Jenkinsfile 中使用 def 和不使用 def 有什么区别?

ycr*_*ycr 6

管道语法有两种类型。Declarative PipelineScripted Pipeline。声明性管道以pipeline {}包装器开始,并且将具有StagesSteps。声明式管道通过更严格的预定义结构限制了用户可用的内容。在脚本化 Pipeline 中,它更接近 Groovy,并且用户在可以执行的操作上将具有更大的灵活性。当您在声明性管道中的块中运行某些内容时Script,脚本步骤会采用该块Scripted Pipeline并在声明性管道中执行该块。基本上,它会Groovy为您运行一个脚本。因此,您的问题可以改写为defGroovy 脚本中的含义。

简而言之,在 Groovy 脚本中,如果省略添加关键字,def则变量将添加到当前脚本的绑定中。因此它将被视为全局变量。如果使用def该变量将被限定作用域,并且您将只能在当前脚本块中使用它。这个问题已经有很多详细的答案了,我就不重复了。