Project 3: A Secure Enterprise Jenkins Platform With JCasC, Kubernetes Agents, SonarQube, Trivy and Approvals
What You Will Build
text
Developers ──► Git host ──webhook──► JENKINS CONTROLLER (Kubernetes, Helm, JCasC)
│ SSO via OIDC, roles per team folder
├─► Ephemeral pod agents (per build)
├─► Vault (short-lived secrets)
├─► SonarQube (quality gate)
├─► Registry + Trivy + Cosign (scan, sign)
└─► Prometheus + Grafana + alerts, backups
Requirements
| Component | Lab choice |
|---|---|
| Kubernetes | kind or minikube (or a cloud test cluster) |
| Identity provider | Keycloak in the same cluster |
| Secrets | HashiCorp Vault in dev mode (lab only) or a Kubernetes secret |
| Quality and scanning | SonarQube Community, Trivy CLI |
| Registry | A local registry or any hosted registry |
| Monitoring | kube-prometheus-stack Helm chart |
Step 1: Deploy Jenkins With Helm
bash
helm repo add jenkins https://charts.jenkins.io && helm repo update
kubectl create namespace jenkins
helm upgrade --install jenkins jenkins/jenkins -n jenkins -f values.yaml
kubectl -n jenkins get pods -w
yaml
# values.yaml
controller:
image:
registry: registry.example.com
repository: ci/jenkins
tag: "lts-jdk21-2026.11" # your image with pinned plugins (see JCasC lesson)
numExecutors: 0
admin:
existingSecret: jenkins-admin
jenkinsUrl: https://jenkins.example.com/
installPlugins: false # plugins are baked into the image
JCasC:
defaultConfig: false
configScripts: {} # we mount our own config from a ConfigMap below
resources:
requests: {cpu: "1", memory: 3Gi}
limits: {memory: 4Gi}
javaOpts: "-XX:MaxRAMPercentage=70 -XX:+HeapDumpOnOutOfMemoryError"
ingress:
enabled: true
hostName: jenkins.example.com
ingressClassName: nginx
tls: [{secretName: jenkins-tls, hosts: [jenkins.example.com]}]
prometheus: {enabled: true}
persistence:
enabled: true
size: 50Gi
agent:
enabled: true
serviceAccount:
create: true
Step 2: JCasC for Security and Teams
yaml
jenkins:
numExecutors: 0
securityRealm:
oic:
clientId: "jenkins"
clientSecret: "${OIDC_CLIENT_SECRET}"
wellKnownOpenIDConfigurationUrl: "https://sso.example.com/realms/corp/.well-known/openid-configuration"
userNameField: "preferred_username"
groupsFieldName: "groups"
authorizationStrategy:
roleBased:
roles:
global:
- {name: admin, permissions: ["Overall/Administer"], entries: [{group: "ci-admins"}]}
- {name: reader, permissions: ["Overall/Read"], entries: [{group: "authenticated"}]}
items:
- name: team-shop
pattern: "shop/.*"
permissions: ["Job/Read", "Job/Build", "Job/Cancel", "Job/Workspace", "Job/Configure", "Credentials/View"]
entries: [{group: "team-shop"}]
- name: team-pay
pattern: "payments/.*"
permissions: ["Job/Read", "Job/Build", "Job/Cancel", "Job/Workspace", "Job/Configure", "Credentials/View"]
entries: [{group: "team-payments"}]
clouds:
- kubernetes:
name: "k8s"
namespace: "jenkins-agents"
jenkinsUrl: "http://jenkins.jenkins.svc.cluster.local:8080"
jenkinsTunnel: "jenkins-agent.jenkins.svc.cluster.local:50000"
containerCapStr: "30"
retentionTimeout: 5
templates:
- name: "default"
label: "k8s"
idleMinutes: 0
containers:
- name: "jnlp"
image: "jenkins/inbound-agent:latest-jdk21"
resourceRequestCpu: "500m"
resourceRequestMemory: "1Gi"
globalNodeProperties:
- envVars:
env:
- {key: "REGISTRY", value: "registry.example.com"}
unclassified:
globalLibraries:
libraries:
- name: "platform-lib"
defaultVersion: "v1.0.0"
retriever:
modernSCM:
scm:
git:
remote: "https://git.example.com/platform/jenkins-shared-lib.git"
credentialsId: "git-readonly"
sonarGlobalConfiguration:
installations:
- name: "sonar-main"
serverUrl: "https://sonar.example.com"
credentialsId: "sonar-token"
security:
scriptApproval:
approvedSignatures: []
jobs:
- script: >
folder('shop') { displayName('Team Shop') }
- script: >
folder('payments') { displayName('Team Payments') }
numExecutors: 0keeps builds off the controller- Folders and role patterns give each team only its area
jenkinsTunneland the internal URL let pod agents connect inside the cluster- The controller config comes from a ConfigMap or from the image, built from Git
Step 3: Secrets From Vault
- Run Vault; enable the Kubernetes auth method or AppRole
- Create a policy that allows read on
secret/data/ci/*only - Store the registry password and tokens in Vault
- Configure the Jenkins HashiCorp Vault plugin credential (AppRole or Kubernetes auth)
- In pipelines, use
withVaultinstead of storing secrets in Jenkins
Step 4: The Golden Path Library Step
groovy
// vars/securePipeline.groovy
def call(Map cfg) {
pipeline {
agent { label 'k8s' }
options { timeout(time: 45, unit: 'MINUTES'); disableConcurrentBuilds(abortPrevious: true) }
stages {
stage('Build and test') { steps { container('jnlp') { sh cfg.buildCommand } } }
stage('Secret and dependency scan') {
parallel {
stage('Secrets') { steps { sh 'gitleaks detect --no-banner --redact' } }
stage('Dependencies') { steps { sh 'trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .' } }
}
}
stage('Sonar') {
steps {
withSonarQubeEnv('sonar-main') { sh cfg.sonarCommand }
timeout(time: 10, unit: 'MINUTES') { waitForQualityGate abortPipeline: true }
}
}
stage('Image, scan, sign') {
when { branch 'main' }
steps {
script {
def image = "${env.REGISTRY}/${cfg.image}:${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}"
sh "docker build -t ${image} ."
sh "trivy image --severity HIGH,CRITICAL --exit-code 1 --ignore-unfixed ${image}"
sh "docker push ${image}"
sh "syft ${image} -o cyclonedx-json > sbom.json"
withCredentials([file(credentialsId: 'cosign-key', variable: 'COSIGN_KEY')]) { sh "cosign sign --yes --key $COSIGN_KEY ${image}" }
archiveArtifacts 'sbom.json'
env.IMAGE = image
}
}
}
stage('Approval') {
when { branch 'main' }
steps { timeout(time: 2, unit: 'DAYS') { input message: "Release ${env.IMAGE}?", submitter: cfg.approvers ?: 'release-managers' } }
}
stage('Deploy') {
when { branch 'main' }
steps { sh "helm upgrade --install ${cfg.app} chart/ -n ${cfg.namespace} --set image.tag=${env.IMAGE.split(':')[-1]} --atomic --wait" }
}
}
post { failure { notifySlack() } }
}
}
groovy
// A team Jenkinsfile
@Library('platform-lib@v1.0.0') _
securePipeline(app: 'shop-api', image: 'team/shop-api', namespace: 'shop-prod',
buildCommand: './mvnw -B verify', sonarCommand: './mvnw -B sonar:sonar')
Step 5: Monitoring and Alerts
- Install
kube-prometheus-stackand aServiceMonitorfor Jenkins metrics - Dashboards: queue size, executor use, build duration, success rate, JVM heap, disk
- Alerts: queue over threshold, no agents available, disk under 15 percent, controller restarts
Step 6: Backups and the Recovery Drill
- Schedule volume snapshots of the Jenkins persistent volume (daily) and keep the config in Git
- Delete the Jenkins pod and watch Kubernetes restore it with the same volume
- Disaster drill: install Jenkins in a new namespace from the Helm values and image, restore a snapshot, confirm jobs and credentials work
- Write down how long it took and who did what
Acceptance Checklist
| Requirement | How to test |
|---|---|
| Login only through SSO | Try the Jenkins local login URL: it should be disabled except the break-glass account |
| Team isolation | A team-shop user cannot see or build payments/ jobs or credentials |
| No builds on the controller | Check executors: controller has zero |
| Secrets safe | Search logs for secret values; fork PR gets no credentials |
| Security gates | A fake secret in code fails the build; a vulnerable image fails the build |
| Approvals | Production deploy waits for release-managers |
| Reproducible | Delete the controller; a new one comes back identical from Git and Helm |
| Observable | Dashboard shows queue and agents; a test alert fires |
Extra Challenges
- Add a Kyverno or admission policy that only runs signed images in production
- Move deployments to Argo CD (GitOps) with Jenkins updating the config repo
- Add a second controller for another business unit using the same Helm values and library
- Automate plugin updates with a scheduled pipeline that builds a new image and tests it in staging
Conclusion
You designed a Jenkins platform, not only a pipeline: Helm on Kubernetes, JCasC and a pinned plugin image, SSO and role-based team folders, ephemeral pod agents, Vault-backed secrets, a golden-path library with scan, quality, signing and approval gates, monitoring, and a tested recovery plan.
Quick Summary: Helm values; JCasC with OIDC + role-based + k8s cloud; Vault; securePipeline golden path; monitoring; backups + recovery drill; acceptance checklist.

