Damien-Amen
Damien-Amen

Reputation: 7512

Getting variables from a different file in Jenkins Pipeline

I have a contants.groovy file as below

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

I have another groovy file that will be called in Jenkins pipeline job

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

But constants."${gitId}" is says "cannot get gitID from null object". How do I get it?

Upvotes: 5

Views: 8670

Answers (2)

张馆长
张馆长

Reputation: 1859

groovy file lib.groovy:

varFoo = "bar"

return this

groovy main:

lib = load "lib.groovy"
print("${lib.varFoo}")

Upvotes: 0

Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10435

It's because they are local variables and cannot be referenced from outside. Use @Field to turn them into fields.

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;

Then in the main script you should load it using load step.

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

You can find more details about variable scope in this answer

Upvotes: 7

Related Questions