如何使用 Jenkins 管道写出环境变量

F.P*_*F.P 3 jenkins jenkins-pipeline

如何writeFile在 Jenkins 管道中写出环境变量?这似乎是一项简单的任务,但我找不到任何有关如何使其工作的文档。

我试过了$VAR${VAR}而且${env.VAR},没有任何效果......?

lvt*_*llo 6

在声明性管道中(使用脚本块 for writeFile),它将如下所示:

pipeline {
    agent any

    environment {
        SENTENCE = 'Hello World\n'
    }

    stages {
        stage('Write') {
            steps {
                script {
                    writeFile file: 'script.txt', text: env.SENTENCE
                }
            }
        }
        
        stage('Verify') {
            steps {
                sh 'cat script.txt'
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

...
[Pipeline] { (Verify)
[Pipeline] sh
[test] Running shell script
+ cat script.txt
Hello World
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)

如果你想避免 groovy,这也可以:

writeFile file: 'script.txt', text: "${SENTENCE}"
Run Code Online (Sandbox Code Playgroud)

要将您的 env var 与文本结合起来,您可以执行以下操作:

...
environment {
    SENTENCE = 'Hello World'
}
...

writeFile file: 'script.txt', text: env.SENTENCE + ' is my newest sentence!\n'
Run Code Online (Sandbox Code Playgroud)