Project 2: Microservices Monorepo Pipeline With a Shared Library, Parallel Tests and Dynamic Agents

CI CD Pipelines with Jenkins 55 min min read Updated: Nov 17, 2026 Advanced
Project 2: Microservices Monorepo Pipeline With a Shared Library, Parallel Tests and Dynamic Agents
Advanced Topic 2 of 3

What You Will Build

text monorepo/ ├─ services/ │ ├─ catalog/ (Java) │ ├─ cart/ (Node.js) │ └─ payments/ (Python) ├─ deploy/ (Helm charts, one per service) ├─ tests/compose/ (docker-compose.yml for integration tests) └─ Jenkinsfile (short: uses the shared library) jenkins-shared-lib/ └─ vars/ ├─ detectChangedServices.groovy ├─ buildService.groovy ├─ testService.groovy ├─ imagePush.groovy └─ monorepoPipeline.groovy

Goal: a push that touches only services/cart builds and tests only cart; a change to shared files (deploy/, library version) builds everything. All services build in parallel on dynamic Kubernetes agents.

Step 1: Detect Changed Services

groovy // vars/detectChangedServices.groovy def call(Map cfg = [:]) { def base = cfg.base ?: (env.CHANGE_TARGET ? "origin/${env.CHANGE_TARGET}" : 'HEAD~1') def root = cfg.root ?: 'services' def allSvcs = sh(script: "ls -1 ${root}", returnStdout: true).trim().split('\n') as List def changed = sh(script: "git diff --name-only ${base}...HEAD || git diff --name-only HEAD~1", returnStdout: true).trim().split('\n') as List def sharedChanged = changed.any { it.startsWith('deploy/') || it.startsWith('tests/') || it == 'Jenkinsfile' } if (sharedChanged || params.BUILD_ALL) { return allSvcs } def result = allSvcs.findAll { svc -> changed.any { it.startsWith("${root}/${svc}/") } } echo "Changed services: ${result}" return result }
On pull requests CHANGE_TARGET is set by multibranch jobs. Fetch the target branch first (git fetch origin ${CHANGE_TARGET}) so the comparison works with a shallow clone.

Step 2: Standard Steps

groovy // vars/buildService.groovy def call(String svc) { dir("services/${svc}") { if (fileExists('pom.xml')) { sh './mvnw -B -q verify' } else if (fileExists('package.json')) { sh 'npm ci --silent && npm test --silent' } else if (fileExists('pyproject.toml')) { sh 'pip install -q -e .[test] && pytest -q --junitxml=report.xml' } else { error "Unknown build type for ${svc}" } } }
groovy // vars/imagePush.groovy def call(String svc, String tag) { def image = "registry.example.com/shop/${svc}:${tag}" withCredentials([usernamePassword(credentialsId: 'registry-creds', usernameVariable: 'U', passwordVariable: 'P')]) { sh "docker build -t ${image} services/${svc}" sh "trivy image --severity CRITICAL --exit-code 1 --ignore-unfixed ${image}" sh 'echo "$P" | docker login registry.example.com -u "$U" --password-stdin' sh "docker push ${image}" } return image }

Step 3: Dynamic Parallel Stages

groovy // vars/monorepoPipeline.groovy def call(Map cfg = [:]) { def services = [] def images = [:] pipeline { agent none options { timeout(time: 60, unit: 'MINUTES'); disableConcurrentBuilds(abortPrevious: true) } parameters { booleanParam(name: 'BUILD_ALL', defaultValue: false, description: 'Build every service') } stages { stage('Detect') { agent { label 'light' } steps { checkout scm script { services = detectChangedServices() } } } stage('Build and test services') { when { expression { services } } steps { script { def branches = [:] services.each { svc -> branches[svc] = { podTemplate(yaml: libraryResource('org/shop/agent-pod.yaml')) { node(POD_LABEL) { checkout scm stage("${svc}: test") { container('tools') { buildService(svc) } } stage("${svc}: image") { container('docker') { images[svc] = imagePush(svc, "${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}") } } } } } } branches.failFast = true parallel branches } } } stage('Integration tests') { when { expression { services && env.BRANCH_NAME == 'main' } } agent { label 'docker' } steps { sh 'docker compose -f tests/compose/docker-compose.yml up -d --wait' sh './tests/run-integration.sh' } post { always { sh 'docker compose -f tests/compose/docker-compose.yml down -v' } } } stage('Deploy staging') { when { expression { services && env.BRANCH_NAME == 'main' } } agent { label 'docker' } steps { script { services.each { svc -> sh "helm upgrade --install ${svc} deploy/${svc} -n shop-staging --set image.tag=${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)} --atomic --wait" } } } } } post { failure { notifySlack() } } } }
groovy // Jenkinsfile in the monorepo @Library('shop-lib@v1.0.0') _ monorepoPipeline()
  • parallel branches runs one branch per changed service, each in its own pod
  • failFast = true stops the rest when one branch fails
  • The images map keeps image names so later stages can use them
  • A pod template stored in the library's resources/ keeps the agent definition in one place

Step 4: The Agent Pod Template

yaml # resources/org/shop/agent-pod.yaml apiVersion: v1 kind: Pod spec: containers: - name: tools image: registry.example.com/ci/tools:2026.11 # JDK 21, Node, Python, Maven wrapper deps command: ["sleep"] args: ["infinity"] resources: requests: {cpu: "1", memory: 2Gi} limits: {memory: 4Gi} - name: docker image: gcr.io/kaniko-project/executor:debug command: ["sleep"] args: ["infinity"] volumeMounts: - {name: docker-config, mountPath: /kaniko/.docker} volumes: - name: docker-config secret: {secretName: registry-dockerconfig}
Docker in pods If your cluster blocks the Docker socket, build images with Kaniko or BuildKit in rootless mode. Then replace docker build with the matching command in imagePush.

Step 5: Integration Test Environment

yaml # tests/compose/docker-compose.yml services: db: image: postgres:16 environment: {POSTGRES_PASSWORD: test, POSTGRES_DB: shop} healthcheck: {test: ["CMD-SHELL", "pg_isready -U postgres"], interval: 3s, retries: 20} catalog: image: registry.example.com/shop/catalog:${TAG:-latest} depends_on: {db: {condition: service_healthy}} cart: image: registry.example.com/shop/cart:${TAG:-latest} depends_on: [catalog] payments: image: registry.example.com/shop/payments:${TAG:-latest}

Step 6: Try It

  1. Create the three small services and the library repository; tag the library v1.0.0
  2. Create a Multibranch Pipeline for the monorepo
  3. Change only services/cart in a pull request: confirm only cart is built
  4. Change deploy/ and confirm all services build
  5. Break a test in payments: confirm other branches stop (fail fast) and the PR shows failure
  6. Merge: watch integration tests and the staging deploy

Self-Check

QuestionAnswer to aim for
How long does a one-service change take compared to a full build?Much shorter: only the changed service runs
What if the library changes?Services pin a library tag; update deliberately and test with a sample pipeline
What if two services must deploy together?Use a combined integration stage, or version APIs with contract tests
Where do pods get registry credentials?A Kubernetes secret mounted into the build pod, never in the library

Conclusion

A monorepo pipeline detects changed services, builds and tests them in parallel in dynamic pod agents, uses a versioned shared library for standard steps, runs integration tests with Docker Compose, and deploys only the changed services. Shared files trigger a full build.

Quick Summary: detectChangedServices; buildService/imagePush steps; dynamic parallel map with podTemplate; failFast; pod yaml in resources; compose integration tests; staged deploy.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators