如何在 Jenkinsfile 中设置和引用变量 [英] How to set and reference a variable in a Jenkinsfile

查看:49
本文介绍了如何在 Jenkinsfile 中设置和引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于我的多分支项目的声明性管道脚本,我想在其中读取文本文件并将结果存储为字符串变量,以供管道中的后续步骤访问.使用片段生成器,我尝试做这样的事情:

I have a declarative pipeline script for my multibranch project in which I would like to read a text file and store the result as a string variable to be accessed by a later step in the pipeline. Using the snippet generator I tried to do something like this:

filename = readFile 'output.txt'

对于哪个 filename 将是我的字符串.

For which filename would be my string.

我在 Jenkins 控制台输出中收到一个错误:

I get an error in the Jenkins console output:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 30: Expected a step @ line 30, column 5.
            filename = readFile 'output.txt'

我是否需要使用 withEnv 步骤将 readFile 的输出设置为 Jenkins 环境变量?如果是,怎么办?

Do I need to use a withEnv step to set the output of readFile to a Jenkins environment variable? If so, how?

谢谢

推荐答案

该错误是因为您只能在 steps 指令内使用管道步骤.我知道的一种解决方法是使用 script 步骤并将任意管道脚本包装在其中并将结果保存在环境变量中,以便以后使用.

The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

所以在你的情况下:

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.FILENAME = readFile 'output.txt'
                }
                echo "${env.FILENAME}"
            }
        }
    }
}

这篇关于如何在 Jenkinsfile 中设置和引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆