在Jenkins Pipeline中从另一个文件获取变量

5

我有一个如下的contants.groovy文件

def testFilesList = 'test-package.xml'
def testdataFilesList = 'TestData.xml'
def gitId = '9ddfsfc4-fdfdf-sdsd-bd18-fgdgdgdf'

我有另一个 Groovy 文件,将在 Jenkins pipeline 作业中调用

def constants
node ('auto111') {
  stage("First Stage") {
    container('alpine') {
      script {
        constants = evaluate readTrusted('jenkins_pipeline/constants.groovy')
        def gitCredentialsId = constants."${gitId}"
      }
    }
  }
}

但是constants."${gitId}"显示“无法从空对象获取gitID”。我该怎么办?

1个回答

6

这是因为它们是局部变量,无法从外部引用。使用@Field将其转换为字段。

import groovy.transform.Field

@Field
def testFilesList = 'test-package.xml'
@Field
def testdataFilesList = 'TestData.xml'
@Field
def gitId = '9ddfsfc4-fdfdf-sdsd-bd18-fgdgdgdf'

return this;

然后在主脚本中,您应该使用load步骤加载它。

script {
    //make sure that file exists on this node
    checkout scm
    def constants = load 'jenkins_pipeline/constants.groovy'
    def gitCredentialsId = constants.gitId
} 

您可以在这个答案中找到有关变量作用域的更多细节。


@Damien-Amen,你应该使用load步骤来加载Groovy文件。我已经更新了答案。 - Vitalii Vitrenko
我尝试了你建议的方法。我成功地加载了文件。但是无论我做什么,都无法从constants.groovy中获取Field。当我只打印变量constants时,它会打印文件的内容。 我尝试过constants."${testdataFilesList}""${constants.testdataFilesList}"constants.testdataFilesList"${constants}".testdataFilesList"${constants}"."${testdataFilesList}""${constants}"."${testdataFilesList}""${constants}".'testdataFilesList'constants.'testdataFilesList' - Damien-Amen
我尝试在constants.groovy中添加return this,但它仍然无法找到该文件中的字段。 - Damien-Amen
@Damien-Amen 我更新了答案。但是没有分号为什么不起作用,这非常奇怪。 - Vitalii Vitrenko
是的。我还使用了 evaluate readTrusted('jenkins_pipeline/constants.groovy') 来使用 lightweight checkout 读取文件,这样我就不必显式地 checkout scm - Damien-Amen
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接