问题
I want to keep my seed job as small as possible and keep all the logic in a central git repository. Also, I have several independent Jenkins instances that then could share the code. How can I load a groovy library in a Jenkins Job DSL script?
Is there something like the Pipeline Remote File Loader Plugin, so that you only need to do fileLoader.fromGit('lib.groovy', 'https://git.repo')
?
回答1:
Hereafter my quicksheet about achieving this in a parameterized Pipeline job, Using Pipeline script from SCM from git.repo
What may be of interest to you:
- loading mecanism :
stash/unstash
- "from SCM" location :
src = "../${env.JOB_NAME}@script/"
Jenkins
Pipeline
Definition: "Pipeline script from SCM"
SCM: Git
Repository URL git.repo
Branches to build */master
Script Path jobs/build.groovy
This project is parameterized:
String Parameter PARAM0
String Parameter PARAM1
git.repo
├── jobs
│ ├── helpers
│ │ └── utils.groovy
│ └── build.groovy
└── scripts
├── build
│ └── do_build.sh
└── inc.sh
Contents : utils.groovy
├── jobs
│ ├── helpers
│ │ └── utils.groovy
def log(msg) {
println("========== " + msg)
}
return this
Contents : build.groovy
├── jobs
│ └── build.groovy
stage ('Init') {
/* Loads */
def src = "../${env.JOB_NAME}@script/"
def helpers_dir = 'jobs/helpers'
def scripts_dir = 'scripts'
/* Stages Scripts */
def do_build = 'build/do_build.sh'
utils = load src + helpers_dir + "/utils.groovy"
dir(src) {
stash name: scripts_dir, includes: "${scripts_dir}/"
}
}
stage ('Build') {
node () {
unstash scripts_dir
build_return = sh (returnStdout: true, script: """
./${scripts_dir}/${do_build} \
"${PARAM0}" \
"${PARAM1}"
""").readLines()
builded = build_return.get(build_return.size()-1).tokenize(',')
utils.log("PARAM0: " + builded[0])
utils.log("PARAM1: " + builded[1])
}
}
Contents : inc.sh
└── scripts
└── inc.sh
#!/bin/sh
## scripts common includes
common=included
Contents : do_build.sh
└── scripts
├── build
│ └── do_build.sh
#!/bin/sh
## includes
. $(dirname $(dirname ${0}))/inc.sh
echo ${common}
## ${0} : PARAM0
## ${1} : PARAM1
echo "${0},${1}"
回答2:
The Job DSL Gradle Example shows how to maintain DSL code in a Git repository.
来源:https://stackoverflow.com/questions/43340106/jenkins-job-dsl-load-groovy-library-from-git-repo