Articles on: Jenkins Service

Jenkins Shared Libraries Tutorial - Reference



Complete examples, troubleshooting, and API reference.


Table of Contents


Reference - Table of Contents


  1. Team-Based Job DSL Examples
  2. Complete Pipeline Examples
  3. API Reference
  4. Troubleshooting
  5. Configuration Reference


Team-Based Job DSL Examples

Reference - Team Based Job DSL Examples

The following examples demonstrate how to create Job DSL scripts for different teams in the modern team-based architecture.


Data Science Team Example

Reference - Data Science Team Example

Filejobs/jenkins-controllers/data-science/src/dsl/groovy/mlPipelines.groovy

String rootFolder = ROOT_FOLDER ?: ''
String team = TEAM ?: 'data-science'

// ML Model Training Pipeline
pipelineJob("${rootFolder}/ml-experiments/model-training") {
displayName('Model Training Pipeline')
description('Train and validate ML models with MLflow tracking')

parameters {
stringParam('MODEL_NAME', 'customer-churn-model', 'Name of the model to train')
choiceParam('ALGORITHM', ['xgboost', 'random-forest', 'neural-network'], 'ML Algorithm to use')
stringParam('DATASET_VERSION', 'v1.0', 'Dataset version from feature store')
booleanParam('ENABLE_HYPERPARAMETER_TUNING', false, 'Enable hyperparameter optimization')
choiceParam('COMPUTE_INSTANCE', ['ml.m5.large', 'ml.m5.xlarge', 'ml.c5.2xlarge'], 'SageMaker instance type')
}

properties {
disableConcurrentBuilds()
buildDiscarder {
strategy {
logRotator {
numToKeepStr('50')
daysToKeepStr('30')
}
}
}
pipelineTriggers {
triggers {
cron {
spec('H 2 * * 1-5') // Daily at 2 AM on weekdays
}
}
}
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/ml-models.git')
credentials('github-pat')
}
branches('main', 'develop')
scriptPath('jenkins-controllers/data-science/src/main/groovy/ml-experiments/model-training-pipeline.groovy')
}
}
}
}
}

// Model Deployment Pipeline
pipelineJob("${rootFolder}/model-deployment/model-serving") {
displayName('Model Serving Deployment')
description('Deploy trained models to various serving platforms')

parameters {
stringParam('MODEL_NAME', '', 'Model name from MLflow registry')
stringParam('MODEL_VERSION', '', 'Model version to deploy')
choiceParam('DEPLOYMENT_TARGET', ['staging', 'production', 'a-b-test'], 'Deployment target environment')
choiceParam('SERVING_PLATFORM', ['sagemaker', 'kubernetes', 'lambda'], 'Model serving platform')
booleanParam('ENABLE_MONITORING', true, 'Enable model drift monitoring')
}

properties {
disableConcurrentBuilds()
authorizationMatrix([
'hudson.model.Item.Build:data-science-team',
'hudson.model.Item.Read:authenticated'
])
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/ml-models.git')
credentials('github-pat')
}
scriptPath('jenkins-controllers/data-science/src/main/groovy/model-deployment/model-serving.groovy')
}
}
}
}
}


Engineering Team Example

Reference - Engineering Example

Filejobs/jenkins-controllers/engineering/src/dsl/groovy/applicationPipelines.groovy

String rootFolder = ROOT_FOLDER ?: ''

// Application CI/CD Pipeline
pipelineJob("${rootFolder}/applications/app-cicd") {
displayName('Application CI/CD Pipeline')
description('Complete CI/CD pipeline for microservices')

parameters {
stringParam('APPLICATION_NAME', '', 'Application name to build and deploy')
stringParam('GIT_BRANCH', 'main', 'Git branch to build')
choiceParam('BUILD_TYPE', ['debug', 'release'], 'Build configuration')
choiceParam('DEPLOYMENT_STRATEGY', ['rolling', 'blue-green', 'canary'], 'Deployment strategy')
booleanParam('RUN_SECURITY_SCAN', true, 'Run security vulnerability scan')
booleanParam('RUN_PERFORMANCE_TESTS', false, 'Run performance tests')
}

properties {
disableConcurrentBuilds()
buildDiscarder {
strategy {
logRotator {
numToKeepStr('100')
daysToKeepStr('30')
}
}
}
pipelineTriggers {
triggers {
githubPush()
}
}
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/applications.git')
credentials('github-pat')
}
branches('main', 'develop', 'feature/*')
scriptPath('jenkins-controllers/engineering/src/main/groovy/applications/deployment-pipeline.groovy')
}
}
}
}
}

// End-to-End Testing Pipeline
pipelineJob("${rootFolder}/testing/e2e-tests") {
displayName('End-to-End Testing Suite')
description('Comprehensive E2E testing across all application components')

parameters {
choiceParam('TEST_SUITE', ['smoke', 'regression', 'full', 'performance'], 'Type of test suite to run')
choiceParam('ENVIRONMENT', ['development', 'staging'], 'Target environment for testing')
stringParam('BROWSER', 'chrome', 'Browser for UI tests (chrome, firefox, safari)')
booleanParam('PARALLEL_EXECUTION', true, 'Execute tests in parallel')
stringParam('TEST_DATA_SET', 'default', 'Test data set to use (default, large, small)')
}

properties {
disableConcurrentBuilds()
pipelineTriggers {
triggers {
cron {
spec('H 6 * * *') // Daily at 6 AM
}
}
}
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/e2e-tests.git')
credentials('github-pat')
}
scriptPath('jenkins-controllers/engineering/src/main/groovy/testing/e2e-testing.groovy')
}
}
}
}
}


DevOps Team Example

Reference - DevOps Team

Filejobs/jenkins-controllers/devops/src/dsl/groovy/infrastructurePipelines.groovy

String rootFolder = ROOT_FOLDER ?: ''

// Terraform Infrastructure Pipeline
pipelineJob("${rootFolder}/infrastructure/terraform-deploy") {
displayName('Terraform Infrastructure Pipeline')
description('Manage cloud infrastructure using Terraform')

parameters {
choiceParam('ACTION', ['plan', 'apply', 'destroy'], 'Terraform action to execute')
choiceParam('WORKSPACE', ['development', 'staging', 'production'], 'Terraform workspace')
stringParam('TERRAFORM_VERSION', '1.5.0', 'Terraform version to use')
booleanParam('AUTO_APPROVE', false, 'Auto-approve apply (development only)')
stringParam('TARGET_RESOURCES', '', 'Specific resources to target (optional)')
}

properties {
disableConcurrentBuilds()
authorizationMatrix([
'hudson.model.Item.Build:devops-team',
'hudson.model.Item.Read:authenticated'
])
buildDiscarder {
strategy {
logRotator {
numToKeepStr('50')
daysToKeepStr('90')
}
}
}
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/infrastructure.git')
credentials('github-pat')
}
branches('main', 'develop')
scriptPath('jenkins-controllers/devops/src/main/groovy/infrastructure/terraform-pipeline.groovy')
}
}
}
}
}

// Kubernetes Cluster Management
pipelineJob("${rootFolder}/platform-engineering/k8s-management") {
displayName('Kubernetes Cluster Management')
description('Deploy and manage Kubernetes resources')

parameters {
choiceParam('CLUSTER', ['dev-cluster', 'staging-cluster', 'prod-cluster'], 'Target Kubernetes cluster')
choiceParam('ACTION', ['deploy', 'update', 'rollback', 'scale'], 'Kubernetes action')
stringParam('NAMESPACE', 'default', 'Target namespace')
stringParam('MANIFEST_PATH', 'k8s/', 'Path to Kubernetes manifests')
booleanParam('DRY_RUN', false, 'Perform dry run only')
}

properties {
disableConcurrentBuilds()
pipelineTriggers {
triggers {
pollSCM {
scmpoll_spec('H/15 * * * *') // Poll every 15 minutes
}
}
}
}

definition {
cpsScm {
scm {
git {
remote {
url('https://github.com/your-org/k8s-manifests.git')
credentials('github-pat')
}
scriptPath('jenkins-controllers/devops/src/main/groovy/platform-engineering/kubernetes-deployment.groovy')
}
}
}
}
}


Complete Examples

Reference - Complete Examples

Microservice Pipeline

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#microservice-pipeline)

Complete production-ready pipeline for microservices.

Filevars/microservicePipeline.groovy

/**
* Standard pipeline for microservices with build, test, scan, and deploy stages.
*/
def call(Map config) {
pipeline {
agent any

options {
timeout(time: 60, unit: 'MINUTES')
timestamps()
buildDiscarder(logRotator(numToKeepStr: '50'))
disableConcurrentBuilds()
}

environment {
SERVICE_NAME = "${config.serviceName}"
DOCKER_REGISTRY = "${config.dockerRegistry ?: 'registry.company.com'}"
IMAGE_NAME = "${DOCKER_REGISTRY}/${SERVICE_NAME}"
}

stages {
stage('Checkout') {
steps {
checkout scm
script {
env.GIT_COMMIT_SHORT = sh(
script: 'git rev-parse --short HEAD',
returnStdout: true
).trim()
}
}
}

stage('Build') {
steps {
script {
log.info("Building ${SERVICE_NAME}")
buildApp(
language: config.language,
buildTool: config.buildTool
)
}
}
}

stage('Test') {
parallel {
stage('Unit Tests') {
steps {
runTests(type: 'unit')
}
}
stage('Integration Tests') {
steps {
runTests(type: 'integration')
}
}
stage('Code Quality') {
steps {
sonarScan(projectKey: SERVICE_NAME)
}
}
}
}

stage('Docker Build') {
steps {
script {
buildDockerImage(
imageName: IMAGE_NAME,
tags: [env.GIT_COMMIT_SHORT, 'latest'],
buildArgs: [
BUILD_DATE: new Date().format('yyyy-MM-dd'),
VERSION: config.version ?: '1.0.0'
]
)
}
}
}

stage('Security Scan') {
steps {
script {
dockerScan(
imageName: "${IMAGE_NAME}:${env.GIT_COMMIT_SHORT}",
failOnCritical: true
)
}
}
}

stage('Push Image') {
steps {
script {
withDockerRegistry(
credentialsId: 'docker-registry-credentials',
url: "https://${DOCKER_REGISTRY}"
) {
sh """
docker push ${IMAGE_NAME}:${env.GIT_COMMIT_SHORT}
docker push ${IMAGE_NAME}:latest
"""
}
}
}
}

stage('Deploy to Dev') {
when {
branch 'develop'
}
steps {
script {
deployToK8s(
namespace: 'development',
deployment: SERVICE_NAME,
image: "${IMAGE_NAME}:${env.GIT_COMMIT_SHORT}"
)
}
}
}

stage('Deploy to Staging') {
when {
branch 'main'
}
steps {
script {
deployToK8s(
namespace: 'staging',
deployment: SERVICE_NAME,
image: "${IMAGE_NAME}:${env.GIT_COMMIT_SHORT}"
)
}
}
}

stage('Smoke Tests') {
when {
anyOf {
branch 'develop'
branch 'main'
}
}
steps {
script {
String env = BRANCH_NAME == 'main' ? 'staging' : 'development'
runSmokeTests(environment: env)
}
}
}
}

post {
always {
junit '**/test-results/**/*.xml'
publishHTML([
reportDir: 'coverage',
reportFiles: 'index.html',
reportName: 'Coverage Report'
])
}
success {
script {
notification {
slack channel: config.slackChannel ?: '#builds'
message "✅ ${SERVICE_NAME} build succeeded"
}
}
}
failure {
script {
notification {
slack channel: config.slackChannel ?: '#build-failures'
message "❌ ${SERVICE_NAME} build failed"
mention '@here'
}
}
}
}
}
}


Usage in Jenkinsfile:

@Library('my-shared-lib@v1.0.0') _

microservicePipeline(
serviceName: 'user-service',
language: 'java',
buildTool: 'gradle',
dockerRegistry: 'registry.company.com',
version: '2.1.0',
slackChannel: '#platform-builds'
)


API Reference

Reference - API Reference

Global Variables (vars/)

Reference - Global Variables


buildApp

Reference - buildApp

Builds applications using various build tools.

Parameters:

  • language (String, required): Programming language ('java', 'node', 'python', 'go')
  • buildTool (String, required): Build tool ('maven', 'gradle', 'npm', 'pip', 'go')
  • skipTests (Boolean, optional, default: false): Skip tests during build

Example:

buildApp(
language: 'java',
buildTool: 'gradle',
skipTests: false
)


buildDockerImage

Reference - buildDockerImage

Builds Docker images with tagging support.

Parameters:

  • imageName (String, required): Docker image name
  • tags (List, optional, default: ['latest']): Image tags
  • buildArgs (Map, optional): Build arguments
  • dockerfile (String, optional, default: 'Dockerfile'): Path to Dockerfile

Example:

buildDockerImage(
imageName: 'myapp',
tags: ['v1.0.0', 'latest'],
buildArgs: [VERSION: '1.0.0']
)


log

Reference - Log

Colored logging with multiple log levels.

Methods:

  • log(message, options): Basic log
  • log.info(message): Info level
  • log.warn(message): Warning level
  • log.error(message): Error level
  • log.success(message): Success level

Example:

log.info('Starting build')
log.warn('Deprecated feature used')
log.error('Build failed')
log.success('Deployment complete')


bash

Reference - Bash

Enhanced bash script execution with error handling.

Parameters:

  • script (String, required): Bash script to execute
  • options (Map, optional):
    • silent (Boolean): Suppress output
    • debug (Boolean): Enable debug mode
    • failFast (Boolean): Exit on first error

Example:

bash '''
echo "Hello World"
ls -la
pwd
'''

bash(
script: 'echo "Silent mode"',
silent: true,
failFast: false
)


Classes (src/)

Reference - Classes


Bash

Reference - Bash

Advanced shell wrapper with output capture.

import com.example.jenkins.shell.Bash

def bash = new Bash(this)
bash.call('Deploy script', '''
kubectl apply -f deployment.yaml
kubectl rollout status deployment/myapp
''')


StringHelper

Reference - StringHelper

String manipulation utilities.

import com.example.jenkins.utils.StringHelper

String camel = StringHelper.toCamelCase('hello-world') // 'helloWorld'
String snake = StringHelper.toSnakeCase('helloWorld') // 'hello_world'
String slug = StringHelper.slugify('Hello World!') // 'hello-world'


DateHelper

Reference - DateHelper

Date/time utilities for pipelines.

import com.example.jenkins.utils.DateHelper

String timestamp = DateHelper.getCurrentTimestamp() // '2025-01-15T10:30:00Z'
String formatted = DateHelper.format(new Date(), 'yyyy-MM-dd')


Troubleshooting

Reference - Troubleshooting

Common Issues

Reference - Common Issues

1. Library Not Loading

Reference - Library Not Loading

Error:

ERROR: Library my-shared-lib not found

Solution:

  • Verify library is configured in Jenkins: Manage Jenkins → System → Global Pipeline Libraries
  • Check repository URL is accessible
  • Ensure credentials are correct
  • Verify branch/tag exists

2. Serialization Errors

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#2-serialization-errors)

Error:

java.io.NotSerializableException: ...

Solution: Use @NonCPS annotation:

import com.cloudbees.groovy.cps.NonCPS

@NonCPS
def processData(List data) {
return data.collect { it * 2 }
}

3. Class Not Found

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#3-class-not-found)

Error:

unable to resolve class com.example.jenkins.Bash

Solution:

  • Ensure class exists in src/ directory with correct package structure
  • Verify file is committed to repository
  • Check import statement matches package declaration
  • Reload Jenkins configuration

4. Permission Denied in Sandbox

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#4-permission-denied-in-sandbox)

Error:

Scripts not permitted to use method ...

Solution:

  • Go to Manage Jenkins → In-process Script Approval
  • Approve the method signature
  • Or disable sandbox mode (not recommended for production)

5. Tests Failing

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#5-tests-failing)

6. Team Configuration Issues

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#6-team-configuration-issues)

Error:

JENKINS_TEAM_NAME must be set (data-science, engineering, devops)

Solution:

  • Set environment variable on Jenkins controller: JENKINS_TEAM_NAME=data-science
  • Verify the team name is one of: data-scienceengineeringdevops
  • Restart Jenkins controller after setting environment variable

Error:

Team-specific DSL scripts not found

Solution:

  • Ensure team directory exists: jenkins-controllers/[team-name]/src/dsl/groovy/
  • Verify DSL files have .groovy extension
  • Check Git repository structure matches expected format
  • Verify branch contains team-specific changes

7. MLflow/SageMaker Issues (Data Science Team)

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#7-mlflowsagemaker-issues-data-science-team)

Error:

MLflow tracking server not accessible

Solution:

  • Check MLFLOW_TRACKING_URI environment variable
  • Verify network connectivity to MLflow server
  • Ensure proper authentication credentials are configured

8. Kubernetes/Docker Issues (Engineering/DevOps Teams)

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#8-kubernetesdocker-issues-engineeringdevops-teams)

Error:

kubectl: command not found

Solution:

  • Install kubectl on Jenkins agents
  • Update agent Docker images with required tools
  • Use Kubernetes plugin for Jenkins instead of shell commands


Debugging Tips

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#debugging-tips)

Team-Specific Debug Mode

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#team-specific-debug-mode)

// In team-specific pipeline
@Library('my-shared-lib@main') _

pipeline {
agent any
environment {
TEAM_DEBUG = 'true'
JENKINS_TEAM_NAME = 'engineering'
}
stages {
stage('Debug Team Config') {
steps {
script {
if (env.TEAM_DEBUG == 'true') {
echo "Team: ${env.JENKINS_TEAM_NAME}"
echo "Available tools: ${teamConfig.getTools(env.JENKINS_TEAM_NAME)}"
echo "Target platforms: ${teamConfig.getPlatforms(env.JENKINS_TEAM_NAME)}"
}
}
}
}
}
}


Debugging Tips

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#debugging-tips-1)

Enable Debug Mode

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#enable-debug-mode)

// In pipeline
@Library('my-shared-lib@main') _

pipeline {
options {
timestamps()
ansiColor('xterm')
}
stages {
stage('Debug') {
steps {
script {
// Print all environment variables
sh 'env | sort'

// Enable bash debug mode
bash(script: 'echo test', debug: true)
}
}
}
}
}


Test Locally

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#test-locally)

# Run tests
./gradlew test

# Run specific test with output
./gradlew test --tests "BashSpec" --info

# Check code quality
./gradlew codenarc

# View coverage
./gradlew jacocoTestReport
open build/reports/jacoco/test/html/index.html


Validate Job DSL

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#validate-job-dsl)

# Test Job DSL syntax
cd jobs
./gradlew test

# Check for deprecated API usage
./gradlew jobDslValidation


Configuration Reference

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#configuration-reference)

Gradle Build Configuration

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#gradle-build-configuration)

Filebuild.gradle

plugins {
id 'groovy'
id 'codenarc'
id 'jacoco'
}

group = 'com.example'
version = '1.0.0'

repositories {
mavenCentral()
}

dependencies {
implementation 'org.codehaus.groovy:groovy-all:3.0.9'
implementation 'com.cloudbees:groovy-cps:1.31'

testImplementation 'org.spockframework:spock-core:2.1-groovy-3.0'
testImplementation 'com.lesfurets:jenkins-pipeline-unit:1.17'
testImplementation 'junit:junit:4.13.2'
}

codenarc {
toolVersion = '3.1.0'
configFile = file('config/codenarc/codenarcMain.groovy')
}

jacoco {
toolVersion = '0.8.8'
}

test {
useJUnit()
finalizedBy jacocoTestReport
}

jacocoTestReport {
reports {
xml.enabled true
html.enabled true
}
}


CodeNarc Configuration

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#codenarc-configuration)

Fileconfig/codenarc/codenarcMain.groovy

ruleset {
description 'CodeNarc rules for Jenkins shared library'

// Basic rules
ruleset('rulesets/basic.xml')
ruleset('rulesets/braces.xml')
ruleset('rulesets/exceptions.xml')
ruleset('rulesets/imports.xml')
ruleset('rulesets/naming.xml')
ruleset('rulesets/unnecessary.xml')

// Custom configurations
DuplicateStringLiteral {
doNotApplyToClassNames = '*Spec,*Test'
ignoreStrings = 'test,build,deploy'
}

LineLength {
length = 120
ignoreImportStatements = true
ignorePackageStatements = true
}

MethodSize {
maxLines = 50
doNotApplyToClassNames = '*Spec,*Test'
}

CyclomaticComplexity {
maxMethodComplexity = 10
maxClassComplexity = 50
}

// Disabled rules
VariableName {
enabled = false // Allow vars like env.GIT_COMMIT
}
}


Jenkins Configuration

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#jenkins-configuration)

Global Pipeline Libraries Setup:

  1. Navigate to: Manage Jenkins → System
  2. Find: Global Trusted Pipeline Libraries
  3. Add library:

Advanced Options:

  • ✅ Allow default version to be overridden
  • ✅ Include @Library changes in job recent changes
  • ⬜ Cache fetched versions on controller for quick retrieval (optional)


Team-Based Controller Configuration

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#team-based-controller-configuration)

Each Jenkins controller should be configured with the appropriate team environment variable:

Data Science Controller:

  • Environment variable: JENKINS_TEAM_NAME=data-science
  • Agents: ML-optimized instances with GPU support
  • Plugins: Python, MLflow, SageMaker

Engineering Controller:

  • Environment variable: JENKINS_TEAM_NAME=engineering
  • Agents: Docker-enabled build agents
  • Plugins: Docker, Kubernetes, SonarQube

DevOps Controller:

  • Environment variable: JENKINS_TEAM_NAME=devops
  • Agents: Infrastructure management agents
  • Plugins: Terraform, Ansible, AWS CLI


Team Environment Variables

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#team-environment-variables)

Team-specific environment variables used in shared libraries:

// Team identification
env.JENKINS_TEAM_NAME // 'data-science', 'engineering', 'devops'

// Data Science specific
env.MLFLOW_TRACKING_URI // MLflow server URL
env.SAGEMAKER_EXECUTION_ROLE // SageMaker execution role ARN
env.FEATURE_STORE_URI // Feature store endpoint

// Engineering specific
env.DOCKER_REGISTRY // Container registry URL
env.KUBERNETES_CLUSTER // Default cluster name
env.SONAR_HOST_URL // SonarQube server URL

// DevOps specific
env.TERRAFORM_BACKEND // Terraform state backend
env.AWS_DEFAULT_REGION // Default AWS region
env.VAULT_ADDR // HashiCorp Vault address

// Common environment variables
env.BUILD_NUMBER
env.BUILD_ID
env.JOB_NAME
env.WORKSPACE
env.BRANCH_NAME
env.GIT_COMMIT


Best Practices Checklist

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#best-practices-checklist)

Development

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#development)

  • ✅ Use semantic versioning (v1.0.0, v2.0.0)
  • ✅ Write tests for all functions
  • ✅ Document with .txt files
  • ✅ Keep functions small and focused
  • ✅ Use proper error handling
  • ✅ Follow DRY principles

Testing

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#testing)

  • ✅ Unit tests for all classes
  • ✅ Test coverage > 70%
  • ✅ Integration tests for complex scenarios
  • ✅ Run tests in CI/CD

Security

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#security)

  • ✅ Never log credentials
  • ✅ Use Jenkins credential store
  • ✅ Scan Docker images
  • ✅ Approve scripts in sandbox
  • ✅ Review shared library changes

Performance

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#performance)

  • ✅ Use @NonCPS for heavy operations
  • ✅ Minimize external calls
  • ✅ Cache when possible
  • ✅ Use parallel stages
  • ✅ Clean up resources in finally blocks


Additional Resources

[](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#additional-resources)


Updated on: 02/11/2025

Was this article helpful?

Share your feedback

Cancel

Thank you!