Usage of Jenkins shared library in Job DSL

3,336 views
Skip to first unread message

tre...@gmail.com

unread,
Aug 17, 2018, 12:04:56 PM8/17/18
to Jenkins Users
Hey,

I am looking for advice how to achieve usage of Jenkins shared library in Job DSL – 
I use this snipped to seed a job whose functionality is in Jenkins file:


job('my-small-test-job') {
parameters {
stringParam('branch', '${branch}')
}
removedJobAction: 'IGNORE'
def releaseScript = readFileFromWorkspace('Jenkinsfile')
steps {
      dsl {
      text(releaseScript)
      }
}
}

The newly created [my-small-test-job] has this content (taken out of the Jenkinsfile): 

@Library('templates')_

stage('Demo') {
    echo 'Hello world'
    jobBuilder {
      nodeLabels = 'linux && test'
      antExtraArgs = 'test -Dtest.suite=com.softwareag.suites.custom.ToolsTestSuite'
}
}

I have a shared library under [templates] that is a generic job builder (the syntax is typical groovy like jenkins pipeline, similar to what is explained here: https://jenkins.io/doc/book/pipeline/shared-libraries/)


When I try to run the newly created [my-small-test-job] I get this: 

Processing provided DSL script
ERROR: startup failed:
script: 1: unable to resolve class Library ,  unable to find class for annotation
 @ line 1, column 1.
   @Library('templates')_
   ^

1 error


The shared library is obviusly not added to classpath. How do I fix this?

Jan Monterrubio

unread,
Aug 26, 2018, 11:04:36 AM8/26/18
to jenkins...@googlegroups.com
Manage Jenkins -> configure system -> global libraries 

You can add your shared library there. 

--
You received this message because you are subscribed to the Google Groups "Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jenkinsci-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jenkinsci-users/6e3b23aa-873b-40c6-9859-c5cd7356611f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

tre...@gmail.com

unread,
Aug 27, 2018, 2:27:16 AM8/27/18
to Jenkins Users
Yep,
My libraries are already configured there, but the DSL script is obviously not working. Perhaps the syntax needs to be different...

Philip Steiner

unread,
Dec 17, 2018, 4:51:39 PM12/17/18
to Jenkins Users
Hi tre..., I know this thread is getting old, but did you ever get an answer or figure out how to use a Jenkins Shared Library in the Job DSL script, or some workaround?

Thanks
Philip

tre...@gmail.com

unread,
Dec 18, 2018, 7:27:57 AM12/18/18
to Jenkins Users
Well, not exactly. I found a workaround by reworking the entire logic.

My landscape is: one master declarative pipeline kicks off multiple child pipeline jobs. 
Both the master and the child pipelines are instances created out of shared libraries (jobBuilder, pipelineBuilder) and I want to be able to run the child items as standalone pipelines (in isolation) as well as running them from master pipeline context (different params).

The child job's Jenkins file looks like this (the syntax is not declarative but scripted - the shared library is loaded on the first line):

library identifier: 'templates@branches/rel/10.4.0.x/build/change-management/jenkinsfiles/templates', retriever: modernSCM([$class: 'SubversionSCMSource', remoteBase: 'SVN', credentialsId: 'USER'])

stage('Run Test Suite') {
    jobBuilder {
nodeLabels = 'linux'
antExtraArgs = 'test -Dtest.suite=com.pcbsys.suites.nJMS.PromotionTests'
jobTimeoutHours = 3
}
}


jobsdsl syntax was used only to create the actual Jenkins child pipeline:

script {
    for (String jobName : allJobs) {
        jobDsl scriptText: """
            pipelineJob('${nirvanaMajor}.${nirvanaMinor}_${devJobPrefix}${jobName}') {
                 parameters {
                    stringParam('branch','${svnBranch}','svn repository url')
                    stringParam('buildmajor',"${nirvanaMajor}",'release major identifier')
                    stringParam('buildminor',"${nirvanaMinor}",'release minor identifier')
                    stringParam('fix', '${env.fix}','fix level')
                    stringParam('buildnumber', '${env.buildNumber}','artifacts build number')
                    stringParam('revision', '${env.buildNumber}','checkout revision')
                    stringParam('parentjob', '${pipelineName}','optional parent job')
                }
                removedJobAction: 'IGNORE'
                definition {
                    cpsScm {
                        scm {
                            svn {
                                location ('${svnBranch}/${jobName}') {
                                    credentials('user')
                                }
                            }
                        }
                        scriptPath('Jenkinsfile') 
                    }
                }
            }
            """.stripIndent()

Philip Steiner

unread,
Dec 18, 2018, 2:28:45 PM12/18/18
to Jenkins Users
Thanks for the detailed followup! Lots to digest. It looks like you were having trouble accessing the Shared Library from generated pipeline scripts, which is a little different from my problem: I want to reference YAML data files stored in the Jenkins Shared Library from inside a Job DSL script, but now it appears that's not possible (at least I don't see anything like @Library for the Job DSL API), so I think I also need to rework the overall logic for my build environment. 

Nick Muzika

unread,
Aug 3, 2019, 8:13:31 PM8/3/19
to Jenkins Users
hi Philip,
It's possible


@Grab
('org.yaml:snakeyaml:1.17')

import org.yaml.snakeyaml.Yaml ......
def params = readFileFromWorkspace(param.getPath())
yamlMap = new Yaml().load(params)
yamlMap.each { key, value ->
....
}

Works for me just use yaml module & groovy. In my case shared libraries are placed in the same repository where the seed job dsl is sitting.


вторник, 18 декабря 2018 г., 14:28:45 UTC-5 пользователь Philip Steiner написал:

Tomas Bjerre

unread,
Aug 10, 2019, 7:09:49 AM8/10/19
to Jenkins Users
Not sure if this helps, but: I needed to share code between Pipeline and Job DSL and I solved it by using Job DSL from Pipeline. I found that easy because using shared library in Pipeline is well documented.

Something like:
...
    stage("Create jobs") {
      jobDsl targets: 'work/jobs/*.groovy',
        removedJobAction: 'DELETE',
        removedViewAction: 'DELETE',
        lookupStrategy: 'SEED_JOB',
        additionalClasspath: [].join('\n'),
        additionalParameters: [repos: repos]
    }
...

Example here:
Reply all
Reply to author
Forward
0 new messages