0

I use a shared jenkins library and clone another git repo from there. That repo contains a jenkinsfile similar to the follwing:

#!/usr/bin/env groovy
@Library('mylib')
import jLib.*

someStage{
    myparam = someValue
}

I want to read "someValue". Currently I'm doing this with a regexp but this way I can only retrieve a String and not more complex values like a map.

In the documentation of Shared jenkins libs values are loaded from a jenkinsfile the following way:

def call(body) {
    // evaluate the body block, and collect configuration into the object
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()
}

How can I extract values from the Jenkinsfile in the workspace in a similar manner? Where does the body come from?

Thank you for your time

herm
  • 14,613
  • 7
  • 41
  • 62
  • I don't think I'm understanding what you are trying to do - read the value of `myparam`? The `call(body)` method is a Groovy method that is taking a function and calling it. The signature can be thought of like `call(Closure body)`, if that helps. – mkobit Dec 05 '17 at 19:28
  • Yes I want to read the value of myparam. – herm Dec 06 '17 at 07:22
  • Basically I want to turn this file in my workspace into a Closure and read the values contained in a similar way to how its shown in the second snippet. But I don't know how. – herm Dec 06 '17 at 07:44

1 Answers1

0

I found a solution.

Map configFromJenkinsfile(jenkinsfile){
    def jenkinsfileConfig = [:]
    def matches = jenkinsfile =~ /(?s)\{(.*?)\}/
    def exec = new GroovyShell(new Binding(jenkinsfileConfig)).evaluate(matches[0][1])
    return jenkinsfileConfig;
}

I tested it with passing jenkinsFile as string (after using String projectJenkinsFile = readFile "Jenkinsfile")

I execute the part in the jenkinsfile with all the assignments (between '{' and '}') in a groovyshell with my map as binding. All assignments without type are caught in the binding and can be accessed.

herm
  • 14,613
  • 7
  • 41
  • 62