简体   繁体   中英

Cannot access Jenkins parameters from a templatized pipeline argument

I cannot access to any Jenkins parameter (ex: A as below) from the scope of myPipelineTemplate .

From the Jenkinsfile file:

library 'myPipelineTemplate'

properties([
    parameters([
        booleanParam(name: 'A', defaultValue: false, description: '')
    ])
])

myPipelineTemplate {
    arg1 = A
    arg2 = true
}

From the pipeline template:

def call(body) {
    def args = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = args
    body()

    echo "$args.arg1" // return (null)
    echo "$args.arg2" // return (true)

    pipeline {
        ...
    }

Any lead ?

EDIT: Jenkins ver. 2.107.1

You are using Closure.DELEGATE_FIRST strategy and the delegate is a Map . Your arg2 = true assigns the property, but the A property lookup is a key lookup on that map which is why the assignment is null . The A property lookup is never done on the owner context which would eventually delegate to params.A .

With your delegation strategy, the invocation sort of looks like this:

delegate.arg1 = delegate.A
delegate.arg2 = true

where delegate is the def args = [:] . The delegate in this case handles the property lookup. The value is null and then it is assigned to delegate.arg1 . Your map after the call is [arg1:null, arg2:true] . If you change it to params.A , it would be like delegate.params.A which will fail with a NullPointerException because delegate.params is null .

To make sure the call is resolved to the owner, you could instead use this.params (see this question/answer for meaning of this in a Closure ):

myPipelineTemplate {
    arg1 = this.params.A
    arg2 = true
}

You could also change the resolution strategy:

body.resolveStrategy = Closure.OWNER_FIRST
delegate.arg1 = A
delegate.arg2 = true

I would recommend just changing your call method from a Closure parameter to. any of:

  1. Map
  2. Domain specific object for your pipeline
  3. Multiple arguments

For example, for Map :

def call(Map args) {
  // ...
} 
myPipelineTemplate([
    arg1: params.A
    arg2: true
])

Workaround:

properties([
    parameters([
        booleanParam(name: 'A', defaultValue: false, description: '')
    ])
])

def params = params  

myPipelineTemplate {
    arg1 = A
    arg2 = true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM