So I have a groovy script called "deployer.groovy" that is in a git repository called "jenkins-pipeline-library". (https://github.com/xyzDev/jenkins-pipeline-library) there is nothing else in this repository just this groovy file in the main branch.
Also, I have a Jenkinsfile that is in a different git repository. I cannot put both of these file in a same Git repository.
(because im not allowed to, the idea is to be able to run this deployer.groovy by using Jenkinsfile so that people dont see the content of the deployer.groovy but be able to use it)
I am trying to load this deployer.groovy in my Jenkinsfile and then run it.
Is there any way to do this? Please any suggestions would be highly appreciated.
CodePudding user response:
Official documentation
Extending with Shared Libraries is the documentation that I would recommend for you to understand and achieve what you need.
Explanation
Jenkins configuration: Go to jenkins-url/configure -> Global Pipeline Libraries in this section you can setup the library: using libraries, retrieval method
Library repository: Shared library repository should have the .groovy files in specific folder structure, for your use case you need this:
(root)
- vars
| - foo.groovy # for global 'foo' variable
| - MyDeclarativePipeline.groovy # for global 'MyDeclarativePipeline' variable
vars/foo.groovy
#!/usr/bin/env groovy
def test() {
// define logic here
}
def deployInternal() {
// define logic here
}
vars/MyDeclarativePipeline.groovy
#!/usr/bin/env groovy
def call() {
/* insert your pipeline here */
pipeline {
agent any
stages {
stage('Test') {
steps {
// input the logic here or
foo.test()
}
}
stage('Deploy Internal') {
steps {
// input the logic here or
foo.deployInternal()
}
}
}
}
}
Jenkinsfile:
@Library('my-shared-library') _
MyDeclarativePipeline()
Note: instead of MyDeclarativePipeline() you can insert the pipeline {...} block which was defined in MyDeclarativePipeline.groovy
CodePudding user response:
There are several ways to achive this.
Git Submodule
Your jenkins-pipeline-library could be git-submodule in other repositories.
git submodule add -b master https://github.com/xyzDev/jenkins-pipeline-library jenkins-pipeline-library
Jenkins: Global Pipeline Libraries
On your Jenkins-Server under Manage Jenkins -> Configure System -> Global Pipeline Libraries you can add your repostitory.
After that in any jenkinsfile you can use it like this
import JenkinsPipelineLibrary // Name depends on the actual name of the file
This is an example from a pipeline script I made:
import utils.build.PipelineUtil
PIPELINE_UTIL = new PipelineUtil()
properties(
[
[
$class: 'BuildDiscarderProperty',
strategy: [$class: 'LogRotator', numToKeepStr: '25']
],
PIPELINE_UTIL.getReleaseTrigger('xxxxx')
]
)
Note: The PipelineUtil is located in the repository under utils/build/PipelineUtil.groovy.
