I'm just starting with using Jenkins declarative pipelines. As I'm supporting a few similar projects I was thinking of putting similar pipeline steps (or even stages) into reusable building blocks. These blocks should be maintained at a central spot and then included by individual pipelines (speak: DRY).
I saw shared libraries as an option for scripted pipelines but I'm not sure if it works for declarative pipelines, too.
Do you know a way to use something like building blocks in Jenkins declarative pipelines?
Example to clarify:
If you got a standard pipeline for Maven projects (e. g. Spring Boot), it looks somewhat like:
pipeline {
agent {
dockerfile true
}
stages {
stage('Build') {
steps {
sh 'mvn -U -DskipTests clean package'
}
}
stage('Test') {
parallel {
stage('Unit Tests') {
steps {
sh 'mvn test'
}
}
stage('Integration Tests') {
steps {
sh 'mvn integration-test'
}
}
}
}
stage('Deploy') {
steps {
sh 'mvn deploy'
}
}
}
}
But instead of copying this to all projects, it would be great if following use cases could be easy handled.
For a project without need to customize it would be good to use it for examle like:
defaultMavenpipeline{}
where defaultMavenpipeline will be replaced by above pipeline (I think this is possible with shared libraries).
For a project with need to customize only some stages would something like this be possible?
pipeline {
defaultDockerAgent{}
stages {
stage('Build') {
steps {
sh 'mvn -U -DskipTests clean package'
// ... customize some stuff ...
}
}
defaultTestStage{}
stage('Deploy') {
steps {
// ... customize some stuff ...
sh 'mvn deploy'
}
}
}
}
Sorry for long post and thank you very much in advance!
You can very much use declarative pipeline with Shared-Library.
Please follow these steps:
1) Create a shared library
vars in above repository. Inside vars directory, create a file sayHello.groovy with the following content:// vars/sayHello.groovy
def call(String name = 'human') {
// Any valid steps can be called from this code.
// Can be used in both scripted and declarative pipeline
echo "Hello, ${name}."
}
2) Configure Jenkins for accessing Shared Library in any pipeline job
master3) Access shared library in your project
Pipeline script section, add the following code:@Library('my-shared-lib')_
pipeline {
agent any
stages {
stage('Info') {
steps {
echo 'Publishing some details here'
}
}
stage('Using shared-library') {
steps {
sayHello 'Alex'
}
}
}
}
That's it. You're done! :)
Note: For the the underscore (_) used in shared-library above in Jenkinsfile, from official link, for Shared Libraries which only define Global Variables (vars/), or a Jenkinsfile which only needs a Global Variable, the annotation pattern @Library('my-shared-library') _ may be useful for keeping code concise. In essence, instead of annotating an unnecessary import statement, the symbol _ is annotated.
Output:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With