> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://support.stacktrack.com/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# Jenkins Shared Libraries Tutorial - Reference



> Complete examples, troubleshooting, and API reference.

## Table of Contents

1. [Team-Based Job DSL Examples](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#team-based-job-dsl-examples)
2. [Complete Pipeline Examples](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#complete-pipeline-examples)
3. [API Reference](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#api-reference)
4. [Troubleshooting](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#troubleshooting)
5. [Configuration Reference](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#configuration-reference)

## Team-Based Job DSL Examples
[Reference Repository - Team Based Job DSL Examples](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - Data Science Team Example](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#data-science-team-example)
**File**: `jobs/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 Repository - Engineering Example](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#engineering-team-example)
**File**: `jobs/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 Repository - DevOps Team](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#devops-team-example)
**File**: `jobs/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 Repository - Complete Examples](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#complete-examples)

### Microservice Pipeline
Complete production-ready pipeline for microservices.
**File**: `vars/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 Repository - API Reference](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#api-reference)

### Global Variables (vars/)
[Reference Repository - Global Variables](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#global-variables-vars)

#### buildApp
[Reference Repository - buildApp](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - buildDockerImage](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - Log](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - Bash](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - Classes](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#classes-src)

#### Bash
[Reference Repository - Bash](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#bash-1)
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 Repository - StringHelper](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - DateHelper](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#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 Repository - Troubleshooting](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#troubleshooting)


### Common Issues
[Reference Repository - Common Issues](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#common-issues)

#### 1. Library Not Loading
[Reference Repository - Library Not Loading](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/docs/reference.md#1-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

**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

**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

**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
#### 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-science`, `engineering`, `devops`
* 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)
**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)
**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
#### 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

#### 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
```
# 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
```
# Test Job DSL syntax
cd jobs
./gradlew test

# Check for deprecated API usage
./gradlew jobDslValidation
```

## Configuration Reference
### Gradle Build Configuration
**File**: `build.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
**File**: `config/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
**Global Pipeline Libraries Setup:**
1. Navigate to: `Manage Jenkins` → `System`
2. Find: `Global Trusted Pipeline Libraries`
3. Add library:
    * **Name**: `my-shared-lib`
    * **Default version**: `main`
    * **Retrieval method**: Modern SCM
    * **Source Code Management**: Git
    * **Project Repository**: `https://github.com/your-org/jenkins-shared-library.git`
    * **Credentials**: Select appropriate credentials
    * **Library Path**: (leave empty)
**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

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

### 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

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

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

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

## Additional Resources

* [**Main Tutorial**](/en/article/jenkins-shared-library-tutorial-1mk4i3k/): Foundation and basics
* [**Advanced Guide**](/en/article/jenkins-shared-library-tutorial-advanced-guide-xpeg0c/): Testing, Job DSL, patterns
* [**Demo Repository**](https://github.com/Servana/jenkins-shared-library-tutorial/blob/main/demo-repository): Working examples
* [**Jenkins Documentation**](https://www.jenkins.io/doc/book/pipeline/shared-libraries/)
* [**Job DSL Plugin**](https://github.com/jenkinsci/job-dsl-plugin/wiki)
* [**Spock Framework**](http://spockframework.org/)
* [**JenkinsPipelineUnit**](https://github.com/jenkinsci/JenkinsPipelineUnit)
