Jenkins
QCA For 3 – 4 Years Exp
Nuthan Gatla
Key Topics Covered:
Pipeline Design s Syntax
Declarative vs. Scripted Pipeline design patterns
Parallelization, parameterization, and dynamic variables
Error handling, retries, and notifications
Shared libraries and code reusability
Best practices for maintainable pipelines
Advanced CI/CD Scenarios
Blue-green/canary deployments
Secrets management C compliance
Performance optimization (parallelism, caching)
Rollback strategies C database migrations
Serverless/cloud-native integrations
Security s Credentials
Credential storage, masking, and injection
RBAC and least-privilege access
Integration with secret managers (Vault)
Agent security and network hardening
Audit trails and compliance
Scalability s Performance
Horizontal/vertical scaling strategies
Resource optimization (caching, parallelization)
Monitoring and bottleneck identification
Microservices and distributed pipeline design
High availability and disaster recovery
Integrations
Version Control: GitHub, GitLab
Cloud Platforms: AWS, Kubernetes, Docker
Testing: Selenium, SonarQube
Notifications: Slack
Infrastructure: Terraform, Helm
Artifact Management: Artifactory, Nexus
Issue Tracking: Jira
Troubleshooting
Log Analysis: Console output, thread dumps, agent logs.
Environment Issues: Paths, permissions, tool versions.
Networking: Firewalls, proxies, SSH/HTTP connectivity.
Plugins: Conflicts, compatibility, rollback strategies.
Credentials s Security: RBAC, masking, SSH key handling.
Plugins s Customization
Plugin development (Maven, extensions, UI)
Dependency management C conflict resolution
UI customization (themes, branding)
Pipeline extensions (shared libraries, custom steps)
Automation (Job DSL, Kubernetes agents)
Best practices for upgrades C maintenance
Best Practices
Pipeline as Code C version control
Security hardening (RBAC, secrets, HTTPS)
Resource optimization (caching, parallelization)
Environment management C conditional logic
Disaster recovery C HA
Compliance (quality gates, audit trails)
Real-World Scenarios
Troubleshooting flaky tests, rollbacks, and resource issues
Security practices (secret masking, RBAC)
Performance optimization (parallelization, caching)
Hybrid/multi-cloud deployments
Monorepo and microservices pipeline design
Monitoring s Logging
Metrics Export: Prometheus, Grafana, JVM monitoring
Log Management: ELK, Splunk, secure log sanitization
Alerting: Slack, email, PagerDuty integration
Auditing: Compliance, user activity tracking
Optimization: Disk cleanup, artifact offloading
1. Pipeline Design s Syntax
Q: Explain the difference between Declarative and Scripted Pipelines.
A:
Declarative Pipeline: Structured, opinionated syntax using pipeline {} blocks. Ideal
for simplicity and readability. Example:
pipeline {
agent any
stages {
stage('Build') { steps { sh 'mvn package' } }
Scripted Pipeline: Flexible, Groovy-based syntax using node {} blocks. Allows
complex logic (e.g., loops, conditionals). Example:
node {
stage('Build') { sh 'mvn package' }
1. How would you structure a Declarative Pipeline to enforce a clean workspace
before every build?
Answer: Use the cleanWs step (from the Workspace Cleanup Plugin) or
the deleteDir() command in the post or options section:
pipeline {
agent any
options {
skipDefaultCheckout(true) // Skip default SCM checkout
stages {
stage('Clean Workspace') {
steps {
cleanWs() // Cleans workspace before proceeding
stage('Build') {
steps { sh 'mvn clean install' }
2. How do you parallelize stages in a Jenkins Pipeline? Provide an example.
Answer: Use the parallel block within a stage to run tasks concurrently, improving build
efficiency:
stage('Test') {
steps {
parallel(
"Unit Tests": {
sh 'mvn test -Dgroups="unit"'
},
"Integration Tests": {
sh 'mvn test -Dgroups="integration"'
}
3. How would you handle dynamic environment variables across stages?
Answer: Use environment {} blocks at the pipeline or stage level and leverage script blocks
for dynamic values:
pipeline {
agent any
environment {
BUILD_VERSION = '1.0.0' // Static value
TIMESTAMP = sh(script: 'date +%Y%m%d', returnStdout: true).trim() // Dynamic value
stages {
stage('Build') {
steps {
sh "echo Building version ${BUILD_VERSION}-${TIMESTAMP}"
4. What is the purpose of the post section, and how would you use it for notifications?
Answer: The post section defines actions based on build status
(e.g., success, failure, always). Example:
post {
success {
slackSend channel: '#builds', message: "Build succeeded: ${env.JOB_NAME} -
${env.BUILD_NUMBER}"
}
failure {
emailext subject: 'Build Failed', body: 'Check ${env.BUILD_URL}', to:
'
[email protected]'
cleanup {
deleteDir() // Clean up workspace after build
5. How do you parameterize a Jenkins Pipeline to accept user inputs?
Answer: Use the parameters block to define inputs, which can be accessed via params:
pipeline {
agent any
parameters {
string(name: 'DEPLOY_ENV', defaultValue: 'dev', description: 'Environment to deploy
to')
choice(name: 'REGION', choices: ['us-east-1', 'eu-west-1'], description: 'AWS region')
stages {
stage('Deploy') {
steps {
sh "echo Deploying to ${params.DEPLOY_ENV} in ${params.REGION}"
}
6. How would you handle a flaky test by retrying it up to 3 times before failing the
build?
Answer: Use the retry step within a script block:
stage('Flaky Test') {
steps {
script {
retry(3) {
sh './run-flaky-test.sh'
7. What is a shared library, and how would you use it to avoid code duplication?
Answer: Shared libraries allow reusable pipeline code across projects. Example:
1. Define a library in Jenkins Global Settings (vars/exampleLib.groovy):
def call(String message) {
echo "Shared Library Message: ${message}"
2. Use it in a Jenkinsfile:
@Library('my-shared-lib') _
pipeline {
agent any
stages {
stage('Demo') {
steps { exampleLib('Hello from shared lib!') }
}
8. How do you enforce a timeout for a long-running stage?
Answer: Use the timeout block to limit execution time:
stage('Long Process') {
steps {
timeout(time: 15, unit: 'MINUTES') {
sh './run-long-process.sh'
2. Advanced CI/CD Scenarios
Q: How would you implement a rollback strategy in a Jenkins pipeline?
A:
Use versioned artifacts (e.g., Docker images tagged with commit-SHA).
Integrate with Infrastructure as Code (Terraform/CloudFormation) to redeploy
previous versions.
Example pipeline stage:
stage('Rollback') {
when { expression { currentBuild.result == 'FAILURE' } }
steps {
sh 'kubectl rollout undo deployment/my-app'
}
1. How would you implement a blue-green deployment strategy using Jenkins?
Answer:
Use Jenkins to orchestrate traffic switching between two identical environments (blue =
current, green = new). Example workflow:
1. Deploy the new version to the green environment.
2. Run smoke/regression tests.
3. Redirect traffic from blue to green using a load balancer (e.g., AWS ALB, Kubernetes
Ingress).
Pipeline Snippet:
stage('Deploy Green') {
steps {
sh 'kubectl apply -f green-deployment.yaml'
sh './run-smoke-tests.sh green'
stage('Switch Traffic') {
steps {
sh 'kubectl patch ingress/app -p
\'{"spec":{"rules":[{"host":"myapp.com","http":{"paths":[{"backend":{"serviceName":"green-
svc"}}]}]}}\''
2. How do you handle database schema migrations safely in a CI/CD pipeline?
Answer:
Use tools like Liquibase or Flyway for version-controlled, idempotent migrations.
Pipeline Steps:
1. Run migrations in a dry-run mode during PR validation.
2. Apply migrations to a staging environment first.
3. Include a rollback step in the pipeline using post conditions.
Pipeline Snippet:
stage('DB Migrate') {
steps {
script {
try {
sh 'flyway migrate'
} catch (err) {
sh 'flyway repair' // Fix migration issues
error "Migration failed: ${err}"
3. How would you design a canary release pipeline in Jenkins?
Answer:
Gradually roll out changes to a subset of users while monitoring metrics (e.g., error rates,
latency):
1. Deploy to 5% of nodes.
2. Run integration tests.
3. Use monitoring tools (Prometheus, New Relic) to validate metrics.
4. Automate full rollout if metrics are within thresholds.
Pipeline Snippet:
stage('Canary Deploy') {
steps {
sh 'kubectl set image deployment/app app=myapp:v2 --replicas=5%'
sleep(time: 10, unit: 'MINUTES') // Monitor metrics
script {
def errorRate = sh(script: 'query-prometheus --metric error_rate', returnStdout:
true).trim()
if (errorRate.toFloat() > 0.1) {
error "Canary failed: error rate ${errorRate}%"
4. How do you securely manage secrets (e.g., API keys) in a Jenkinsfile?
Answer:
Use Jenkins Credentials Binding Plugin with withCredentials.
Avoid hardcoding secrets by referencing credential IDs.
For cloud-native secrets, integrate with HashiCorp Vault using the Vault Plugin.
Example:
stage('Deploy') {
environment {
AWS_ACCESS_KEY = credentials('aws-access-key-id')
steps {
withCredentials([string(credentialsId: 'prod-db-password', variable: 'DB_PASS')]) {
sh 'docker login -u $USER -p $DB_PASS registry.example.com'
5. How would you optimize a slow pipeline with 100+ test suites?
Answer:
Parallelize Tests: Split suites across multiple agents.
Use Caching: Cache dependencies (e.g., Maven .m2, npm node_modules).
Distributed Builds: Use Kubernetes pods or EC2 dynamic agents.
Pipeline Snippet:
stage('Parallel Tests') {
parallel {
stage('Test Group 1') {
agent { label 'linux' }
steps { sh './run-tests.sh group1' }
stage('Test Group 2') {
agent { label 'windows' }
steps { sh './run-tests.sh group2' }
6. How do you enforce compliance (e.g., audits, approvals) in a pipeline?
Answer:
Use Input steps for manual approvals.
Integrate with SonarQube for quality gates.
Log all pipeline activities to an audit system (e.g., Splunk).
Pipeline Snippet:
stage('Deploy to Prod') {
steps {
input message: 'Approve deployment?', ok: 'Deploy'
sh './deploy-to-prod.sh'
post {
always {
archiveArtifacts 'logs/**/*.log'
splunkSend logFile: 'pipeline_audit.log'
7. How would you implement a rollback strategy for a failed deployment?
Answer:
Immutable Artifacts: Roll back by redeploying the previous version.
Infrastructure as Code: Use Terraform/CloudFormation to revert changes.
Pipeline Logic:
post {
failure {
script {
if (env.DEPLOY_ENV == 'prod') {
sh './rollback.sh v1.2.3' // Revert to last stable version
slackSend channel: '#alerts', message: "Rollback triggered for ${env.BUILD_URL}"
8. How do you integrate Jenkins with serverless architectures (e.g., AWS Lambda)?
Answer:
Use the AWS CLI or Serverless Framework in pipeline steps.
Deploy Lambda functions via SAM/CDK.
Pipeline Snippet:
stage('Deploy Lambda') {
steps {
withAWS(region: 'us-east-1', credentials: 'aws-cred') {
sh 'sam build'
sh 'sam deploy --guided'
3. Security s Credentials
Q: How do you securely manage secrets in Jenkins?
A:
Use Jenkins Credentials Plugin (stores secrets encrypted).
For advanced use cases, integrate HashiCorp Vault using the Vault Plugin:
withVault(configuration: [vaultUrl: 'https://vault.example.com'], vaultSecrets: [[path:
'secret/data/jenkins', secretValues: [[vaultKey: 'api-key']]]]) {
sh 'echo ${API_KEY} | deploy.sh'
Avoid hardcoding secrets in Jenkinsfiles.
1. How does Jenkins store credentials securely, and what are the risks of mishandling
them?
Answer:
Jenkins encrypts credentials using AES and stores them in the credentials.xml file
(or a secrets directory).
Risks: Hardcoding secrets in plain text, logging credentials accidentally, or granting
excessive permissions.
Best Practice: Use the Credentials Binding Plugin or withCredentials in pipelines
to avoid exposing secrets in logs.
2. How would you restrict access to sensitive jobs or credentials using Role-Based
Access Control (RBAC)?
Answer: Use the Role-Based Authorization Strategy Plugin:
1. Define global roles (e.g., admin, developer).
2. Create item/agent roles to restrict access to specific jobs or folders.
3. Assign users/groups to roles.
Example: Restrict access to a "Prod-Deploy" job to only users in the prod-
admins group.
3. How do you securely inject credentials into a Jenkins Pipeline?
Answer: Use the withCredentials block to bind secrets to environment variables:
pipeline {
agent any
stages {
stage('Deploy') {
steps {
withCredentials([usernamePassword(
credentialsId: 'aws-credentials',
usernameVariable: 'AWS_ACCESS_KEY',
passwordVariable: 'AWS_SECRET_KEY'
)]) {
sh 'aws configure set aws_access_key_id $AWS_ACCESS_KEY'
sh 'aws configure set aws_secret_access_key $AWS_SECRET_KEY'
4. How would you prevent secrets from being exposed in Jenkins console logs?
Answer:
Use withCredentials or credentials() to mask secrets in logs automatically.
Avoid using echo or sh with secret variables.
Enable Mask Passwords Plugin to redact sensitive text.
5. Explain how to integrate Jenkins with HashiCorp Vault for dynamic secrets
management.
Answer: Use the HashiCorp Vault Plugin:
1. Configure Vault server details in Jenkins.
2. Use withVault to fetch secrets dynamically:
stage('Fetch DB Creds') {
steps {
withVault(
configuration: [vaultUrl: 'https://vault.example.com'],
vaultSecrets: [[path: 'secret/db', secretValues: [
[vaultKey: 'username', envVar: 'DB_USER'],
[vaultKey: 'password', envVar: 'DB_PASS']
]]]
){
sh 'echo "User: $DB_USER, Pass: $DB_PASS"'
6. How do you secure Jenkins agents to prevent unauthorized access?
Answer:
Use SSH keys for agent communication instead of passwords.
Restrict agent nodes to specific jobs using labels and RBAC.
Run agents in isolated environments (e.g., Docker, Kubernetes) with minimal
privileges.
Enable encryption for agent-to-controller communication (JNLP4 protocol).
7. How would you audit credential usage in Jenkins?
Answer:
Use the Audit Trail Plugin to log credential access and job executions.
Review credentials.xml change history in version control (if Jenkins config is stored
as code).
Integrate with SIEM tools (e.g., Splunk, ELK) for centralized monitoring.
8. What steps would you take to harden a Jenkins instance?
Answer:
1. Enable HTTPS for the Jenkins dashboard.
2. Disable legacy protocols (JNLP3) and use JNLP4.
3. Limit plugin installations to trusted sources.
4. Regularly update Jenkins and plugins.
5. Use the Matrix Authorization Strategy Plugin to fine-tune permissions.
6. Set up CSRF protection in "Configure Global Security".
G. How do you handle secrets for distributed builds across multiple agents?
Answer:
Store secrets centrally (e.g., Jenkins credentials store, Vault).
Use the Credentials Binding Plugin to inject secrets into agent environments.
Ensure agents run in secure networks (e.g., VPN, private subnets).
10. How would you rotate credentials programmatically in Jenkins?
Answer:
Use the Credentials API with scripts (Groovy/Python) to update credentials.
Example Groovy script for the Script Console:
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
def creds = new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL,
'aws-credentials',
'Updated AWS creds',
'new-access-key',
'new-secret-key'
systemStore.addCredentials(Domain.global(), creds)
4. Scalability s Performance
Q: How do you optimize Jenkins for large-scale deployments?
A:
Use Jenkins Agents (distribute builds across worker nodes).
Implement Parallel Stages:
stage('Tests') {
parallel {
stage('Unit Tests') { steps { sh 'mvn test' } }
stage('Integration Tests') { steps { sh 'mvn verify' } }
Leverage Pipeline Shared Libraries to reuse code across projects.
Configure Jenkins Configuration as Code (JCasC) for scalable, version-controlled
setups.
1. How would you scale Jenkins to handle 500+ concurrent jobs?
Answer:
Horizontal Scaling: Use distributed builds with multiple agents (static or
dynamic).
Dynamic Agents: Leverage cloud resources (e.g., Kubernetes pods, AWS EC2 Spot
Instances) with plugins like Kubernetes Plugin or EC2 Fleet Plugin.
Master Node Optimization:
o Keep the Jenkins master lightweight (avoid running builds on it).
o Use Jenkins Configuration as Code (JCasC) for efficient setup.
o Increase JVM heap size and enable garbage collection tuning.
2. How do you reduce build times for large monorepo projects?
Answer:
Incremental Builds: Use tools like git diff to identify changed modules and build
only those.
Caching: Cache dependencies (e.g., Maven, npm) using Artifactory or Nexus.
Parallel Stages: Split tests and builds across parallel agents.
Distributed File Systems: Use shared storage (e.g., NFS, S3) for large artifacts.
Pipeline Snippet:
stage('Build Changed Modules') {
steps {
script {
def changedModules = sh(script: 'git diff --name-only HEAD~1 | grep "src/"',
returnStdout: true).trim()
parallel changedModules.collectEntries { module ->
["Build ${module}": {
sh "mvn clean install -pl ${module}"
}]
}
3. How would you prevent resource contention between Jenkins agents?
Answer:
Label-Based Allocation: Assign jobs to agents with specific labels (e.g., linux-
large, windows-gpu).
Limit Executors: Restrict the number of executors per agent to avoid overloading.
Resource Allocation Plugins: Use the Yet Another Docker Plugin or Kubernetes
Plugin to dynamically provision agents based on resource requests.
4. How do you monitor Jenkins performance and identify bottlenecks?
Answer:
Metrics Plugins: Use Prometheus Metrics Plugin to export Jenkins metrics (queue
time, executor usage).
Log Analysis: Monitor logs with Elasticsearch or Splunk for errors or slow
operations.
APM Tools: Integrate with New Relic or Datadog to track JVM health and plugin
performance.
Jenkins Health Advisor: Use built-in checks for disk space, memory, and plugin
conflicts.
5. How would you design a Jenkins pipeline for a microservices architecture with 50+
services?
Answer:
Shared Libraries: Reuse common logic (e.g., build, test, deploy) across services.
Fan-Out/Fan-In: Trigger parallel builds for each service, then aggregate results.
Dependency Management: Use a dependency graph to build services in the
correct order.
Dynamic Pipelines: Generate pipelines programmatically using Groovy scripts.
Example:
def services = ['service-a', 'service-b', 'service-c']
stage('Build Microservices') {
steps {
script {
parallel services.collectEntries { service ->
["Build ${service}": {
build job: "${service}-pipeline", parameters: [string(name: 'BRANCH', value: 'main')]
}]
6. How do you optimize agent utilization in a Kubernetes-based Jenkins setup?
Answer:
Pod Templates: Define resource requests/limits for CPU and memory
in podTemplate.
Auto-Scaling: Use Kubernetes Horizontal Pod Autoscaler (HPA) to scale agent pods
based on load.
Ephemeral Agents: Terminate idle agents after a timeout to save resources.
Node Affinity: Schedule resource-heavy jobs on nodes with GPU/SSD.
Declarative Pipeline Example:
pipeline {
agent {
kubernetes {
label 'jenkins-agent'
yaml '''
spec:
containers:
- name: jnlp
resources:
requests:
cpu: "1"
memory: "2Gi"
'''
stages { ... }
7. How would you handle a long build queue causing delays?
Answer:
Priority Sorter Plugin: Prioritize critical jobs.
Scale Agents Dynamically: Use cloud providers to spin up agents during peak
times.
Optimize Pipeline Efficiency:
o Reduce unnecessary stages.
o Use lightweight containers for builds.
o Pre-warm agents with frequently used tools.
8. What strategies ensure high availability (HA) for Jenkins?
Answer:
Master HA: Use active/passive setup with shared storage (e.g., EFS, NFS)
for JENKINS_HOME.
Backup s Restore: Regularly back up configurations using ThinBackup Plugin.
Disaster Recovery: Replicate Jenkins to a secondary region with tools like Jenkins
Configuration as Code (JCasC).
Stateless Agents: Ensure agents are ephemeral and auto-recoverable.
G. How do you manage secrets at scale across hundreds of pipelines?
Answer:
Centralized Secrets Management: Use HashiCorp Vault or AWS Secrets
Manager with Jenkins plugins.
Role-Based Access: Restrict credential usage via RBAC.
Templated Pipelines: Use shared libraries to inject secrets uniformly.
10. How would you reduce disk I/O on the Jenkins master?
Answer:
Externalize Workspaces: Store workspaces on fast, external storage (e.g., SSD,
network-attached storage).
Cleanup Policies: Use Workspace Cleanup Plugin to delete old workspaces.
Log Rotation: Compress and archive logs periodically.
Avoid Archiving Large Artifacts: Use artifact repositories (e.g., Nexus, S3) instead.
5. Integrations
Q: How would you integrate Jenkins with AWS?
A:
withAWS(region: 'us-east-1', credentials: 'aws-creds') {
s3Upload(file: 'app.jar', bucket: 'my-bucket')
For ECS/EKS deployments:
sh 'aws ecs update-service --cluster my-cluster --service my-service --force-new-
deployment'
1. How would you trigger a Jenkins Pipeline on a Git commit using webhooks?
Answer:
GitHub/GitLab Integration: Use the GitHub Plugin or GitLab Plugin.
Configure a webhook in the repository to send a POST request to Jenkins
on push events.
In the Jenkins job, enable the GitHub hook trigger for GITScm polling option.
Example Webhook URL:
https://<JENKINS_URL>/github-webhook/
Pipeline Snippet:
pipeline {
triggers {
GitHubPushTrigger() // Requires GitHub Plugin
stages { ... }
2. How do you integrate Jenkins with Docker for building and publishing images?
Answer:
Use the Docker Pipeline Plugin or shell commands with the Docker CLI.
Best Practices:
o Use a Docker-in-Docker (DinD) sidecar container for isolated builds.
o Scan images for vulnerabilities with Trivy or Clair before pushing.
Pipeline Snippet:
stage('Build C Push Image') {
steps {
script {
docker.withRegistry('https://registry.example.com', 'docker-creds') {
def image = docker.build("myapp:${env.BUILD_NUMBER}", "./Dockerfile")
image.push()
3. How would you deploy to Kubernetes using Jenkins?
Answer:
Use the Kubernetes CLI (kubectl) or Kubernetes Plugin.
Steps:
1. Configure Kubernetes credentials in Jenkins.
2. Apply manifests or Helm charts in the pipeline.
Pipeline Snippet:
stage('Deploy to Kubernetes') {
steps {
withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
sh 'kubectl apply -f k8s/deployment.yaml --kubeconfig $KUBECONFIG'
4. How do you integrate Jenkins with AWS for serverless deployments?
Answer:
Use the AWS SDK, AWS CLI, or Pipeline: AWS Steps Plugin.
Example: Deploy a Lambda function using SAM:
stage('Deploy Lambda') {
steps {
withAWS(region: 'us-east-1', credentials: 'aws-cred') {
sh 'sam build'
sh 'sam deploy --stack-name my-stack --capabilities CAPABILITY_IAM'
5. How would you run Selenium tests in Jenkins using Docker containers?
Answer:
Use the Docker Pipeline Plugin to spin up Selenium Grid containers.
Pipeline Snippet:
stage('Selenium Tests') {
steps {
script {
docker.image('selenium/standalone-chrome').withRun('-p 4444:4444') { c ->
docker.image('maven:3.8.4').inside("--link ${c.id}:selenium") {
sh 'mvn test -Dselenium.host=selenium'
6. How do you integrate Jenkins with SonarQube for code quality checks?
Answer:
1. Install the SonarQube Scanner Plugin.
2. Configure SonarQube server details in Jenkins.
3. Add a pipeline step:
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'sonar-scanner -Dsonar.projectKey=myapp'
7. How would you send Slack notifications for build status?
Answer: Use the Slack Notification Plugin:
post {
success {
slackSend channel: '#builds', message: "SUCCESS: ${env.JOB_NAME}
(${env.BUILD_NUMBER})", color: 'good'
failure {
slackSend channel: '#builds', message: "FAILED: ${env.JOB_NAME}
(${env.BUILD_NUMBER})", color: 'danger'
8. How do you integrate Jenkins with Terraform for infrastructure provisioning?
Answer:
Use the Terraform Plugin or execute Terraform CLI commands.
Pipeline Snippet:
stage('Provision Infrastructure') {
steps {
dir('terraform') {
sh 'terraform init'
sh 'terraform apply -auto-approve'
G. How would you integrate Jenkins with Jira for ticket updates?
Answer: Use the Jira Plugin to transition issues or add comments:
stage('Update Jira') {
steps {
jiraIssue id: 'PROJ-123', action: 'Transition', transitionId: '31' // Move to "Done"
jiraComment id: 'PROJ-123', comment: "Build ${env.BUILD_NUMBER} deployed to
production."
10. How do you integrate Jenkins with Artifactory for artifact storage?
Answer: Use the Artifactory Plugin to publish and resolve artifacts:
stage('Publish Artifact') {
steps {
rtUpload(
serverId: 'artifactory-server',
spec: '''
"files": [{
"pattern": "target/*.jar",
"target": "myapp-repo/"
}]
'''
6. Troubleshooting
Q: A Jenkins build is failing with “No space left on device.” How do you resolve it?
A:
Clean up workspace and old builds using the Workspace Cleanup Plugin.
Add a post-build cleanup step:
post {
always {
cleanWs()
Monitor disk space with Prometheus/Grafana using the Metrics Plugin.
1. A build is failing with a vague error. How would you debug it?
Answer:
Check Console Output: Start with the build’s Console Output for detailed logs.
Verbose Logging: Add sh 'set -x' (Bash) or bat 'echo on' (Windows) to scripts for
step-by-step logging.
Reproduce Locally: Run the failing command locally in the same environment (e.g.,
Docker container).
Isolate Stages: Temporarily comment out stages to identify the root cause.
2. Jenkins agents are going offline intermittently. How would you troubleshoot?
Answer:
1. Check Agent Logs: Review agent.log for connectivity errors
(e.g., java.net.ConnectException).
2. Network Diagnostics:
o Verify firewall rules allow JNLP4 ports (default: TCP 50000).
o Test connectivity with telnet <master-ip> 50000.
3. Resource Issues: Check agent CPU/memory usage (e.g., htop, docker stats).
4. Reconnect Script: Use a cron job to restart the agent service if it disconnects.
3. A pipeline is stuck indefinitely. What steps would you take?
Answer:
Thread Dump: Navigate to Manage Jenkins > System Log > Thread Dump to identify
deadlocks.
Check Input Steps: Look for input steps waiting for user approval.
Kill Stuck Builds: Use the Script Console to abort the build:
Jenkins.instance.getItemByFullName("job-name/PR-123")
.getBuildByNumber(42)
.finish(hudson.model.Result.ABORTED, new java.io.IOException("Manually aborted"))
Agent Timeouts: Ensure timeout blocks are configured for long-running steps.
4. Jenkins master is slow/unresponsive. How do you diagnose the issue?
Answer:
1. JVM Health:
o Check JVM heap usage in Manage Jenkins > System Information (e.g., -
Xmx settings).
o Generate a heap dump with jmap -dump:format=b,file=heapdump.hprof
<pid>.
2. Disk I/O: Monitor disk usage with df -h (clean up old workspaces with Workspace
Cleanup Plugin).
3. Plugins: Disable resource-heavy plugins (e.g., Ant Plugin) temporarily.
4. Garbage Collection: Add GC flags to JAVA_OPTS (e.g., -XX:+UseG1GC -
XX:+PrintGCDetails).
5. A credential is not being injected into a pipeline. What could be wrong?
Answer:
Incorrect Credential ID: Verify the ID matches the stored credential in Manage
Jenkins > Credentials.
Scope Issues: Ensure the credential has Global scope (not restricted to a folder).
Masking: Check logs for [ERROR] and ensure secrets aren’t accidentally printed
(use withCredentials).
Agent Permissions: Confirm the agent has access to the credential (RBAC
restrictions).
6. How would you resolve a "No such file or directory" error in a pipeline?
Answer:
Workspace Check: Use sh 'pwd CC ls -la' to verify the file exists in the workspace.
SCM Checkout: Ensure the checkout scm step succeeded.
Path Case Sensitivity: Check for case-sensitive paths (e.g., src/ vs Src/ on Linux).
Agent File Systems: Verify shared volumes (e.g., NFS) are mounted correctly.
7. A plugin update broke Jenkins. How would you recover?
Answer:
1. Disable the Plugin: Rename its .jpi file in $JENKINS_HOME/plugins/ to .jpi.disabled.
2. Rollback: Restore the previous plugin version from backup (e.g., ThinBackup
Plugin).
3. Script Console: If Jenkins won’t start, use the Jenkins CLI or Docker to disable
plugins:
java -jar jenkins-cli.jar -s http://localhost:8080/ disable-plugin faulty-plugin
4. Compatibility: Check plugin versions against the Jenkins core version.
8. A Git checkout fails with "Permission denied (publickey)". How do you fix it?
Answer:
SSH Agent: Use the SSH Agent Plugin to load the correct key:
stage('Checkout') {
steps {
sshagent(['github-ssh-key']) {
checkout scm
Key Permissions: Verify the key has 600 permissions on the agent.
GitHub Access: Confirm the key is added to the GitHub account’s SSH keys.
G. How would you troubleshoot a pipeline that works locally but fails on Jenkins?
Answer:
Environment Parity: Replicate the Jenkins environment locally (e.g., Docker image,
JDK version).
Tool Paths: Check installations (e.g., mvn -version, node -v) on the agent.
User Permissions: Ensure Jenkins has write access to directories
(e.g., /var/lib/jenkins/workspace).
Proxy Issues: If Jenkins uses a proxy, configure it in Manage Jenkins > Plugin
Manager > Advanced.
10.A user can’t access a job despite having permissions. What’s wrong?
Answer:
RBAC Misconfiguration: Check folder-level permissions with the Role-Based
Plugin.
Matrix Auth: Verify the user/group is added in Manage Jenkins > Configure Global
Security.
Caching Issues: Restart Jenkins to apply permission changes.
AD/LDAP Sync: If using LDAP, ensure group memberships are up-to-date.
7. Plugins s Customization
Q: How do you extend Jenkins functionality using plugins? Give an example.
A:
Example: Integrate SonarQube for code quality:
1. Install the SonarQube Scanner Plugin.
2. Configure SonarQube server in Jenkins global settings.
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'mvn sonar:sonar'
1. What are some essential Jenkins plugins, and how have you used them?
Answer:
Blue Ocean: Modern UI for visualizing pipelines.
Pipeline Utility Steps: File operations, JSON/YAML parsing.
Credentials Binding: Securely inject secrets into pipelines.
Docker Pipeline: Build, run, and manage containers.
Job DSL: Programmatically create jobs via code.
Example:
// Job DSL to create a freestyle job
job('example-job') {
steps {
shell('echo "Hello from Job DSL!"')
2. How would you create a custom Jenkins plugin?
Answer:
1. Setup: Use the Maven archetype:
mvn archetype:generate -Dfilter=io.jenkins.archetypes:
2. Define Extension: Extend hudson.Extension and implement logic (e.g., a new build
step).
3. UI Binding: Use @DataBoundConstructor for Jenkins UI forms.
4. Build s Deploy: Package with mvn package and copy the .hpi file
to $JENKINS_HOME/plugins.
3. How do you safely upgrade Jenkins plugins without breaking existing jobs?
Answer:
Test in Staging: Mirror production in a staging environment first.
Check Compatibility: Use the Jenkins Plugin Compatibility Tool.
Rollback Plan: Backup $JENKINS_HOME/plugins with the ThinBackup Plugin.
Incremental Upgrades: Avoid bulk updates; upgrade one plugin at a time.
4. How would you resolve a plugin dependency conflict?
Answer:
1. Diagnose: Check Manage Jenkins > System
Log for NoSuchMethodError or ClassNotFoundException.
2. Isolate: Use mvn dependency:tree in custom plugins to identify conflicting libraries.
3. Fix:
o Exclude transitive dependencies in pom.xml.
o Downgrade the conflicting plugin to a compatible version.
5. How can you customize the Jenkins UI (e.g., themes, branding)?
Answer:
Simple Theme Plugin: Override CSS/JS for logos, colors, and fonts.
Custom CSS Injection: Use the User CSS Plugin for per-user styling.
Branding Hook: Modify jenkins.model.JenkinsLocationConfiguration via Groovy:
Jenkins.instance.setSystemMessage('Welcome to My Jenkins!')
6. How do you extend Jenkins pipelines with custom steps using plugins?
Answer:
1. Define Global Variable: Create a vars/myStep.groovy file in a shared library.
2. Implement Logic:
def call(String message) {
echo "Custom Step: ${message}"
3. Use in Pipeline:
myStep('Hello from custom step!')
7. How would you enforce code quality gates using plugins in a pipeline?
Answer: Integrate SonarQube Scanner and Warnings Next Generation plugins:
stage('Quality Gate') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'sonar-scanner'
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
8. How do you use the Job DSL plugin to automate job creation?
Answer:
1. Seed Job: Create a pipeline job that runs a DSL script.
2. Generate Jobs:
folder('CI') {
displayName('Continuous Integration Jobs')
pipelineJob('CI/build-job') {
definition {
cps {
script(readFileFromWorkspace('pipelines/build.Jenkinsfile'))
}
G. How would you customize Jenkins agents using plugins?
Answer:
Kubernetes Plugin: Define custom pod templates with tools pre-installed.
NodeLabel Parameter Plugin: Let users choose agents by label.
SSH Agent Plugin: Dynamically provision agents over SSH.
Example Pod Template:
podTemplate(
containers: [containerTemplate(name: 'maven', image: 'maven:3.8.4')],
volumes: [hostPathVolume(hostPath: '/var/run/docker.sock', mountPath:
'/var/run/docker.sock')]
){
node(POD_LABEL) {
container('maven') {
sh 'mvn clean install'
10. How do you customize email notifications using the Email-ext Plugin?
Answer:
post {
always {
emailext(
subject: '${PROJECT_NAME} - Build #${BUILD_NUMBER} - ${BUILD_STATUS}',
body: readFileFromWorkspace('email-template.html'),
to: '[email protected]',
attachLog: true
8. Best Practices
Q: What are Jenkins pipeline best practices for a production environment?
A:
Use Declarative Pipelines for readability.
Version-control Jenkinsfiles in Git.
Limit script approvals in "In-process Script Approval" for security.
Use timeouts and retries:
stage('Deploy') {
steps {
retry(3) {
timeout(time: 10, unit: 'MINUTES') {
sh './deploy.sh'
}
1. Why is "Pipeline as Code" considered a best practice, and how do you implement it?
Answer:
Benefits: Version control, reproducibility, auditability, and collaboration.
Implementation:
o Store Jenkinsfile in SCM (e.g., Git) alongside application code.
o Use Declarative Pipelines for readability and structure.
o Example:
// Jenkinsfile
pipeline {
agent any
stages {
stage('Build') { steps { sh 'mvn clean install' } }
stage('Test') { steps { sh 'mvn test' } }
2. How do you ensure Jenkins pipelines are maintainable across teams?
Answer:
Shared Libraries: Centralize reusable code (e.g., logging, notifications).
Modularization: Break pipelines into smaller stages or functions.
Documentation: Add comments in Jenkinsfile and use a README for pipeline
usage.
Standardization: Enforce naming conventions (e.g., branch names, job prefixes).
3. What security best practices do you follow for Jenkins instances?
Answer:
RBAC: Use Role-Based Authorization Strategy Plugin to restrict permissions.
Credential Management: Never hardcode secrets; use withCredentials or integrate
with HashiCorp Vault.
HTTPS: Secure Jenkins UI with SSL/TLS.
Plugin Audits: Remove unused plugins and keep others updated.
4. How do you optimize resource usage in Jenkins?
Answer:
Lightweight Agents: Run builds in ephemeral containers (Docker/Kubernetes).
Parallelization: Split tests/stages across agents using parallel.
Caching: Cache dependencies (e.g., Maven, npm) using Artifactory or Nexus.
Agent Labels: Assign jobs to agents with specific resources (e.g., gpu-node).
Example:
stage('Parallel Tests') {
parallel {
stage('Unit Tests') { steps { sh './run-unit-tests.sh' } }
stage('Integration Tests') { steps { sh './run-integration-tests.sh' } }
5. How do you handle environment-specific configurations (e.g., dev vs. prod)?
Answer:
Parameterized Pipelines: Use parameters to accept environment names.
Configuration Files: Store environment variables in version-controlled files
(e.g., env-config.yaml).
Conditional Logic:
stage('Deploy') {
when { expression { params.ENV == 'prod' } }
steps { sh './deploy-prod.sh' }
6. What strategies ensure fast feedback in CI pipelines?
Answer:
Fail Fast: Run quick unit tests before slower integration tests.
Incremental Builds: Only rebuild changed modules (e.g., using git diff).
Preview Environments: Spin up ephemeral environments for PR validation.
Notifications: Alert teams immediately via Slack/email on failure.
7. How do you manage Jenkins configuration at scale?
Answer:
Jenkins Configuration as Code (JCasC): Define Jenkins settings in YAML for
consistency.
# jenkins.yaml
jenkins:
securityRealm:
ldap:
configurations:
- server: "ldap.example.com"
Backup: Use the ThinBackup Plugin for scheduled backups.
Infrastructure as Code (IaC): Deploy Jenkins masters/agents via Terraform/Ansible.
8. How do you ensure high availability for Jenkins?
Answer:
Master HA: Use active/passive setup with shared storage (e.g., EFS, NFS)
for JENKINS_HOME.
Stateless Agents: Use dynamic agents (Kubernetes/EC2) to auto-recover from
failures.
Disaster Recovery: Regularly test restoring from backups in a secondary region.
G. What logging and monitoring practices do you follow?
Answer:
Centralized Logs: Ship logs to ELK or Splunk using the Logstash Plugin.
Metrics: Export Jenkins metrics to Prometheus for dashboards.
Alerts: Set up thresholds for disk usage, queue length, or failed builds.
Example:
post {
always {
archiveArtifacts artifacts: '**/target/*.log'
splunkSend logFile: 'build.log'
10. How do you enforce code quality and compliance in pipelines?
Answer:
Quality Gates: Integrate SonarQube to block builds with critical issues.
Static Analysis: Use Checkstyle, ESLint, or Bandit in linting stages.
Approval Workflows: Require manual input for production deployments.
Audit Trails: Use the Audit Trail Plugin to log pipeline activities.
Example:
stage('Quality Gate') {
steps {
withSonarQubeEnv('sonar-server') {
sh 'sonar-scanner'
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true // Fail if quality checks fail
G. Real-World Scenarios
Q: How would you trigger a Jenkins job from a GitHub PR?
A:
Use the GitHub Pull Request Plugin or GitHub Webhooks:
1. Configure a webhook in GitHub pointing to JENKINS_URL/github-webhook/.
2. Use a pipeline job with a triggers block:
pipeline {
triggers {
GitHubPullRequestTrigger()
// stages...
1. Scenario: Flaky Tests Causing Random Build Failures
Problem: A pipeline intermittently fails due to unstable tests. How would you resolve this?
Answer:
Retry Mechanism: Use the retry step for flaky test stages.
Test Isolation: Run flaky tests in parallel with parallel to isolate failures.
Test Reporting: Integrate the JUnit Plugin to track flaky tests over time.
Pipeline Snippet:
stage('Flaky Tests') {
steps {
retry(3) { // Retry up to 3 times
sh './run-flaky-tests.sh'
2. Scenario: A Critical Production Deployment Failed. Rollback Needed
Problem: A deployment caused downtime. How would you automate rollback?
Answer:
Immutable Artifacts: Always deploy versioned artifacts (e.g., Docker tags).
Pipeline Logic: Use the post section to trigger rollback on failure.
Pipeline Snippet:
post {
failure {
script {
if (params.ENVIRONMENT == 'prod') {
sh 'kubectl rollout undo deployment/myapp' // Revert to previous version
slackSend channel: '#alerts', message: "Rollback triggered: ${env.BUILD_URL}"
}
}
3. Scenario: Jenkins Agents Run Out of Disk Space Frequently
Problem: Agents crash due to full disks. How would you prevent this?
Answer:
Workspace Cleanup: Use the Workspace Cleanup Plugin to delete old files post-
build.
Ephemeral Agents: Run agents in Docker/Kubernetes with emptyDir volumes.
Monitoring: Set up alerts for disk usage with Prometheus and Grafana.
Pipeline Snippet:
post {
always {
cleanWs() // Clean workspace after every build
4. Scenario: Secrets Exposed in Console Logs
Problem: Credentials appear in Jenkins logs. How would you fix this?
Answer:
Masking: Use withCredentials to bind secrets and auto-mask them.
Log Filtering: Install the Mask Passwords Plugin.
Audit: Review pipeline steps for accidental echo or print of secrets.
Pipeline Snippet:
withCredentials([string(credentialsId: 'db-password', variable: 'DB_PASS')]) {
sh 'echo "Connecting to DB..."' // $DB_PASS is masked in logs
}
5. Scenario: A Pipeline Takes 2 Hours Due to Sequential Stages
Problem: Slow feedback loop. How would you optimize?
Answer:
Parallelization: Split tests/builds using parallel.
Distributed Builds: Use multiple agents for independent stages.
Caching: Cache dependencies (e.g., npm, Maven).
Pipeline Snippet:
stage('Build C Test') {
parallel {
stage('Frontend') {
agent { label 'frontend' }
steps { sh 'npm run build' }
stage('Backend') {
agent { label 'backend' }
steps { sh 'mvn clean install' }
6. Scenario: A Plugin Update Broke All Pipelines
Problem: Jobs fail after a plugin upgrade. How would you recover?
Answer:
Rollback: Use the ThinBackup Plugin to restore the previous plugin version.
Diagnose: Check $JENKINS_HOME/logs/error.log for compatibility errors.
Isolation: Disable the faulty plugin via the Jenkins CLI:
java -jar jenkins-cli.jar disable-plugin faulty-plugin
7. Scenario: Deploying to Multiple Clouds (AWS s Azure)
Problem: Need a unified pipeline for hybrid cloud deployments.
Answer:
Parameterization: Let users select cloud providers via parameters.
Shared Libraries: Abstract cloud-specific logic into reusable functions.
Pipeline Snippet:
stage('Deploy') {
steps {
script {
if (params.CLOUD == 'aws') {
aws.deploy()
} else if (params.CLOUD == 'azure') {
azure.deploy()
8. Scenario: High Jenkins Master Load Causing Timeouts
Problem: Master node CPU usage is consistently at 90%+.
Answer:
Offload Builds: Run all jobs on agents; keep the master idle.
Optimize GC: Tune JVM flags (e.g., -XX:+UseG1GC -Xmx4g).
Scale Horizontally: Use a Jenkins setup with multiple masters (active/passive).
G. Scenario: CI/CD Pipeline for a Monorepo with 50+ Microservices
Problem: Building all services on every commit is inefficient.
Answer:
Incremental Builds: Use git diff to detect changed services.
Dependency Graph: Build services in order based on dependencies.
Fan-Out Pipeline: Trigger sub-pipelines for each changed service.
Pipeline Snippet:
stage('Detect Changes') {
steps {
script {
def changes = sh(script: 'git diff --name-only HEAD~1', returnStdout: true)
def services = changes.tokenize('\n').findAll { it.startsWith('services/') }
services.each { service ->
build job: "deploy-${service}", wait: false
10. Scenario: Unauthorized Access to Sensitive Jobs
Problem: Developers can trigger production deployments.
Answer:
RBAC: Use the Role-Based Plugin to restrict access.
Approval Workflows: Require manual input for production stages.
Pipeline Snippet:
stage('Deploy to Prod') {
steps {
input message: 'QA Lead, approve deployment?', submitter: 'qa-lead'
sh './deploy-to-prod.sh'
10. Monitoring s Logging
Q: How do you monitor Jenkins pipeline performance?
A:
Use the Prometheus Plugin to expose metrics (e.g., build duration, queue length).
Visualize in Grafana with dashboards.
Log aggregation via ELK Stack or OpenTelemetry (OTel):
stage('Logs') {
steps {
sh 'docker logs my-container | tee app.log'
otelSendLogs(file: 'app.log')
1. How would you monitor Jenkins performance and resource usage?
Answer:
Metrics Plugins: Use the Prometheus Metrics Plugin to expose Jenkins metrics
(e.g., queue length, executor usage, build times) for scraping by Prometheus.
Dashboards: Visualize metrics in Grafana or the Monitoring Plugin for real-time
insights.
JVM Health: Monitor heap usage and garbage collection via JMX or tools like
VisualVM.
Example Prometheus Config:
# prometheus.yml
scrape_configs:
- job_name: 'jenkins'
metrics_path: '/prometheus'
static_configs:
- targets: ['jenkins.example.com:8080']
2. How do you centralize Jenkins logs for analysis?
Answer:
ELK Stack: Use the Logstash Plugin to ship logs to Elasticsearch.
Splunk: Forward logs via the Splunk Plugin or HTTP Event Collector (HEC).
Cloud Solutions: Stream logs to AWS CloudWatch or GCP Stackdriver.
Pipeline Snippet for Log Archiving:
post {
always {
archiveArtifacts artifacts: '**/target/*.log' // Archive build logs
script {
splunkSend logFile: 'build.log' // Send logs to Splunk
3. How would you alert the team about failed builds or system outages?
Answer:
Slack/Email Integration: Use the Slack Notification Plugin or Email-ext Plugin for
alerts.
Prometheus Alerts: Define alert rules in Prometheus and route them via
Alertmanager.
Custom Scripts: Trigger webhooks to tools like PagerDuty.
Example Alerting in Pipeline:
post {
failure {
slackSend channel: '#alerts', message: "Build ${env.BUILD_NUMBER} failed:
${env.BUILD_URL}"
emailext body: "Check logs: ${env.BUILD_URL}", subject: 'Build Failure', to:
'
[email protected]'
4. How do you track build trends (e.g., pass/fail rates, duration) over time?
Answer:
Jenkins API: Extract build data using curl or Groovy scripts:
curl -s "http://jenkins.example.com/job/my-job/api/json" | jq '.builds[].result'
Custom Dashboards: Use the Jenkins Job DSL Plugin to generate reports.
Third-Party Tools: Integrate with Datadog or New Relic for historical analysis.
5. How would you diagnose a slow-running pipeline using logs?
Answer:
1. Console Output: Check timestamps in the build’s console log to identify slow
stages.
2. Thread Dumps: Generate thread dumps via Manage Jenkins > System Log > Thread
Dump to spot deadlocks.
3. Pipeline Timings: Use the Pipeline: Stage View Plugin to visualize stage durations.
Example Log Analysis:
stage('Build') {
steps {
sh 'date +%s > start_time.txt' // Log start time
sh 'mvn clean install'
sh 'date +%s > end_time.txt' // Log end time
6. How do you monitor Jenkins agent health and connectivity?
Answer:
Agent Metrics: Track agent status (online/offline), load, and disk usage via
Prometheus.
Heartbeat Checks: Run periodic ping or curl checks from agents to the master.
Log Monitoring: Parse agent logs (agent.log) for errors
like java.net.ConnectException.
Example Prometheus Query:
jenkins_agent_online_value{agent="linux-agent"} == 0 // Alert if agent goes offline
7. How would you audit user activity and pipeline executions?
Answer:
Audit Trail Plugin: Log user actions (job creation, deletions, config changes).
Splunk Integration: Forward audit logs to Splunk for compliance reporting.
Custom Scripts: Use the Jenkins API to track build history and user activity.
Example API Call:
curl -s "http://jenkins.example.com/audit/events" | jq '.events[] | select(.userId=="alice")'
8. How do you monitor security threats (e.g., failed login attempts)?
Answer:
Security Logs: Monitor $JENKINS_HOME/logs/security.log for brute-force attacks.
Fail2Ban: Integrate with OS-level tools to block suspicious IPs.
Plugins: Use the SSH Monitoring Plugin to track SSH access to agents.
Example Groovy Script for Security Checks:
import hudson.security.*
def authStrategy = Jenkins.instance.getSecurityStrategy()
if (authStrategy instanceof GlobalMatrixAuthorizationStrategy) {
println "RBAC is enabled."
} else {
println "WARNING: Insecure security strategy!"
G. How do you ensure logs don’t expose sensitive data (e.g., credentials)?
Answer:
Masking: Use withCredentials to inject secrets and auto-mask them in logs.
Log Filters: Install the Mask Passwords Plugin to redact sensitive text.
Code Reviews: Enforce policies to prevent echo or print of secrets.
Pipeline Example:
withCredentials([string(credentialsId: 'api-key', variable: 'API_KEY')]) {
sh 'curl -H "Authorization: Bearer $API_KEY" https://api.example.com' // $API_KEY is
masked
}
10. How would you monitor and optimize disk usage on the Jenkins master?
Answer:
Metrics: Track jenkins_disk_usage via Prometheus.
Cleanup Policies: Use the Workspace Cleanup Plugin or cron jobs to delete old
builds.
Artifact Management: Offload artifacts to S3 or Nexus instead of storing them
locally.
Example Cleanup Script:
pipeline {
post {
always {
cleanWs() // Clean workspace after build
script {
currentBuild.rawBuild.getParent().getBuilds().each { build ->
if (build.number < currentBuild.number - 50) { // Keep last 50 builds
build.delete()