Best Practices Guide - Jenkins as Code
Recommended practices for using Jenkins as Code automation framework
Best Practices Guide
Recommended practices for using Jenkins as Code automation framework
π Related Guides:
- Setup Guide - Complete Jenkins setup and configuration
- JobGenie Job Creation Guide - Step-by-step job creation
- Architecture Documentation - System architecture overview
- JobGenie Reference - Complete technical reference
π Table of Contents
- Configuration Management
- Job Creation
- Security Practices
- Version Control
- Monitoring & Observability
- Disaster Recovery
- Team Collaboration
βοΈ Configuration Management
1. Use Environment-Specific Variables
β DO:
# group_vars/packer_al2023_aarch64_devops_jenkins.yml
jenkins_location:
url: "https://jenkins-{{ environment }}.mcloud.com/"
β DONβT:
# Hardcoding values
jenkins_location:
url: "https://jenkins-prod.mcloud.com/" # Wrong for all environments
2. Organize Variables Logically
β DO:
# Group related variables
jenkins_onboarding:
amazon:
mcloud:
jobs: [ /* ... */ ]
env: ["nonprod", "prod"]
β DONβT:
# Scattered configuration
jenkins_mcloud_jobs: [ /* ... */ ]
jenkins_mcloud_env: ["nonprod", "prod"]
jenkins_amazon_mcloud: [ /* ... */ ]
3. Use Sensible Defaults
β DO:
jobgenie:
default:
HOME_DIR: prod
GROUP: "v4" # Current version group
ENV: "prod" # Environment name
jobs:
- NAME: "my-service"
CONFIGS:
APP_REPO: "my-service"
APP_BRANCH: "production"
β DONβT:
jobgenie:
default:
GROUP: null # No default
ENV: "" # Empty default
jobs:
- NAME: "my-service"
CONFIGS:
APP_REPO: "hardcoded-repo-name" # Not flexible
4. Document Custom CONFIGS
β DO:
jobgenie:
default:
HOME_DIR: prod
GROUP: "v4"
ENV: "prod"
jobs:
- NAME: "my-service"
CONFIGS:
# Custom template for beta features
# Purpose: Enable template-based Jenkinsfiles for testing
# Usage: Set CICD_TEMPLATE_NAME to use custom template
CICD_TEMPLATE_NAME: "beta-template"
APP_REPO: "my-service"
β DONβT:
# Undocumented custom CONFIG
CONFIGS:
CICD_TEMPLATE_NAME: "beta-template" # What is this?
π© Job Creation
1. Follow Naming Conventions
β DO:
jobgenie:
default:
HOME_DIR: prod
GROUP: "v4"
ENV: "prod"
jobs:
- NAME: "user-service"
- NAME: "payment-service"
- NAME: "order-service"
β DONβT:
# Inconsistent naming
jobs:
- NAME: "UserService" # PascalCase
- NAME: "payment_service" # snake_case
- NAME: "orderService" # camelCase
2. Use Appropriate Job Types
β DO:
# Standard pipeline job (default)
jobgenie:
default:
HOME_DIR: prod
GROUP: "v4"
ENV: "prod"
jobs:
- NAME: "my-service"
CONFIGS:
APP_REPO: "my-app"
APP_BRANCH: "master"
# Freestyle job when needed
jobs:
- NAME: "database-migration"
CONFIGS:
JOB_TYPE: "freestyle"
SERVICE: "database-migration"
APP_REPO: "migrations"
SCRIPT: |
echo "Run migrations"
β DONβT:
# Using freestyle for standard application
jobs:
- NAME: "my-service"
CONFIGS:
JOB_TYPE: "freestyle" # Should use default pipeline
SCRIPT: |
# Unnecessary script
3. Group Related Jobs
β DO:
# Group related jobs in one file per environment
# File: amazon/mcloud/prod/jobs/mcloud-prod-jobs.yml
jobgenie:
default:
HOME_DIR: prod
GROUP: "v4"
ENV: "prod"
jobs:
- NAME: "service-1"
CONFIGS:
APP_REPO: "app1"
- NAME: "service-2"
CONFIGS:
APP_REPO: "app2"
β DONβT:
# Don't create separate files for each job
# Instead, group related jobs together
4. Minimize Job Parameters
β DO:
jobs:
- NAME: "my-service"
PARAMETERS:
- { name: 'GitBranch', string: 'production', description: 'Application branch.' }
- { name: 'DeployVersion', string: 'latest', description: 'Version to deploy.' }
CONFIGS:
APP_REPO: "my-service"
β DONβT:
jobs:
- NAME: "my-service"
PARAMETERS:
- { name: 'PARAM1', string: '', description: 'Param 1' }
- { name: 'PARAM2', string: '', description: 'Param 2' }
- { name: 'PARAM3', string: '', description: 'Param 3' }
# ... 20 more parameters (too many!)
π Security Practices
1. Use Role-Based Access Control
β DO:
# Granular permissions
overall_read_users:
amazon:
mcloud:
- user: "dev"
qa:
- user: "qa-user"
β DONβT:
# Overly broad permissions
overall_read_users:
amazon:
mcloud:
- user: "*" # Everyone has access
2. Store Secrets Securely
β DO:
- Use Jenkins Credentials Plugin
- Use AWS Secrets Manager
- Use Ansible Vault for sensitive variables
β DONβT:
- Hardcode passwords in files
- Commit secrets to Git
- Share credentials via email
3. Regular Security Audits
β DO:
- Review access permissions quarterly
- Audit credential usage
- Check for unused credentials
- Review audit logs
β DONβT:
- Set and forget security
- Ignore security warnings
- Skip access reviews
4. Follow Least Privilege
β DO:
# Minimum required permissions
permissionTemplates:
- name: "build"
permissions:
- "Job/Build"
- "Job/Read"
- "View/Read"
β DONβT:
# Excessive permissions
permissionTemplates:
- name: "build"
permissions:
- "Overall/Administer" # Too much!
- "Job/Delete"
- "Credentials/Manage"
π Version Control
1. Use Feature Branches
β DO:
# Create feature branch
git checkout -b feature/onboard-new-service
# Make changes
# Commit and push
git commit -m "Onboard new-service-api"
git push origin feature/onboard-new-service
# Create Pull Request
β DONβT:
# Direct commits to main
git checkout main
# Make changes
git commit -m "Quick fix" # No review!
git push origin main
2. Write Meaningful Commit Messages
β DO:
git commit -m "Onboard payment-service to mcloud nonprod
- Add payment-service-api to JobGenie
- Configure Docker build args
- Set up ArgoCD integration"
β DONβT:
git commit -m "fix"
git commit -m "update"
git commit -m "changes"
3. Review Changes Before Merging
β DO:
- Create Pull Request
- Request review from team
- Address feedback
- Merge after approval
β DONβT:
- Merge without review
- Skip testing
- Ignore feedback
4. Tag Releases
β DO:
# Tag stable versions
git tag -a v1.0.0 -m "Initial stable release"
git push origin v1.0.0
β DONβT:
- Forget to tag releases
- Use unclear version numbers
- Tag unstable code
π Monitoring & Observability
1. Enable Build Notifications
β DO:
# Configure notifications in Jenkins system config
jenkins_slack_notifier:
botUser: false
room: "devops-alerts"
teamDomain: "https://yourteam.slack.com/"
tokenCredentialId: "SlackToken"
β DONβT:
# Disable notifications
jenkins_slack_notifier:
enabled: false # No visibility
2. Monitor Key Metrics
β DO:
- Track build success rate
- Monitor deployment frequency
- Measure mean time to recovery
- Track job execution time
β DONβT:
- Ignore failing builds
- Skip monitoring setup
- No alerting configured
3. Set Up Logging
β DO:
# Enable audit trail
jenkins_audit_trail:
logBuildCause: true
logCredentialsUsage: true
logFile: "/var/log/jenkins/audit-trail.log"
β DONβT:
- Disable logging
- No log retention policy
- Logs not centralized
4. Configure Alerts
β DO:
- Set up build failure alerts
- Configure deployment alerts
- Monitor system health
- Alert on security events
β DONβT:
- No alerting configured
- Ignore alerts
- Alert fatigue
π‘οΈ Disaster Recovery
1. Regular Backups
β DO:
# Configure automated backups
jenkins_s3_backup_dir: "s3://bucket-name/backup/jenkins"
β DONβT:
- No backup strategy
- Manual backups only
- No backup testing
2. Test Recovery Procedures
β DO:
- Test full recovery quarterly
- Document recovery steps
- Verify backup integrity
- Practice disaster scenarios
β DONβT:
- Never test recovery
- Outdated documentation
- Unknown recovery time
3. Version Control as Source of Truth
β DO:
- All configs in Git
- Git is primary backup
- Regular Git backups
- Multiple Git remotes
β DONβT:
- Rely only on Jenkins backups
- No Git backup
- Single point of failure
π₯ Team Collaboration
1. Document Changes
β DO:
- Update documentation with changes
- Add comments for complex logic
- Document custom configurations
- Maintain changelog
β DONβT:
- Make undocumented changes
- Assume knowledge
- Skip documentation
2. Share Knowledge
β DO:
- Conduct training sessions
- Share best practices
- Document common issues
- Create runbooks
β DONβT:
- Keep knowledge siloed
- No knowledge sharing
- Tribal knowledge only
3. Standardize Processes
β DO:
- Use standard templates
- Follow naming conventions
- Consistent job structure
- Standardized workflows
β DONβT:
- Every team does it differently
- No standards
- Inconsistent patterns
4. Regular Reviews
β DO:
- Quarterly architecture reviews
- Monthly best practices review
- Weekly team sync
- Continuous improvement
β DONβT:
- No regular reviews
- Set and forget
- No feedback loop
π― Performance Optimization
1. Optimize Job Execution
β DO:
- Use appropriate Jenkins agents
- Set build timeouts
- Limit concurrent builds
- Clean workspace regularly
β DONβT:
- Run all jobs on master
- No timeout limits
- Unlimited concurrent builds
- Never clean workspace
2. Cache Dependencies
β DO:
- Cache Docker layers
- Cache Maven/Gradle dependencies
- Cache Node.js modules
- Use build cache
β DONβT:
- Download dependencies every time
- No caching strategy
- Slow builds
3. Optimize Resource Usage
β DO:
- Right-size Jenkins agents
- Monitor resource usage
- Optimize build scripts
- Use efficient tools
β DONβT:
- Over-provision resources
- No resource monitoring
- Inefficient builds
π Additional Resources
π Related Documentation
- π Main Documentation - Complete Jenkins as Code framework overview
- ποΈ Architecture Documentation - System architecture and design
- βοΈ JobGenie Guide - JobGenie usage and examples
- π DevOps as a Service - Self-service CI/CD platform guide
- π§ Setup Guide - Setup and configuration guide
- π Quick Reference - Quick reference guide
π§ Navigation
Related Topics:
- Review the Architecture for system design patterns
- Learn JobGenie for job creation best practices
- See DevOps as a Service for self-service workflows
Maintained by the DevOps Team
βBest practices are not rules, but guidelines for successβ
Last Updated: January 15, 2024
Version: 1.0.0
Related Documentation
More from Tools
Architecture Documentation - Jenkins as Code
Comprehensive architecture guide for Jenkins as Code automation framework
DevOps as a Service - Automated CI/CD Management
Transforming Jenkins from a bottleneck to a self-service platform for develop...
JobGenie - Complete Job Creation Guide
Step-by-step guide to creating and configuring Jenkins jobs using JobGenie YA...
JobGenie - Complete Guide
Your friendly Jenkins job generator - Comprehensive guide to JobGenie job gen...
Quick Reference Guide - Jenkins as Code
Quick reference for common tasks and configurations in Jenkins as Code
Jenkins as Code - Complete Setup Guide
Step-by-step guide to set up Jenkins as Code with plugins, access control, an...
Jenkins as Code - Enterprise CI/CD Automation
Complete Jenkins automation framework with Infrastructure as Code, Configurat...
BG Deployer
Automated blue-green deployment for zero-downtime AWS releases
DevOps Tools & Utilities | Hari Prasad
Custom-built DevOps tools for automation, monitoring, deployment, and security
JobGenie Getting Started
Your DevOps Superpower Unleashed - Transform CI/CD with YAML-driven Jenkins j...
JobGenie
Your DevOps Superpower Unleashed - Transform CI/CD with YAML-driven Jenkins j...
mCert
SSL certificate monitoring with Slack/email alerts & Telegram
mTracker
Real-time Linux user activity monitoring with Slack notifications
mWatcher
Server health monitoring for CPU, memory, disk with alerting
Sample DevOps Tool Documentation
A comprehensive guide to using our sample DevOps tool for automation and moni...
Typography Demo
Demonstration of enhanced typography features in the documentation template
Related Blog Posts
JobGenie: Transform Jenkins Job Creation with Jobs as Code
Learn how to integrate JobGenie into your existing Jenkins instance to create jobs as code using ...
OpenResty Production Setup: Supercharge with Lua-Based Metrics and Monitoring
Complete guide to deploying production-ready OpenResty with advanced Lua-based metrics collection...
KEDA on EKS: Complete Guide to Event-Driven Autoscaling with Real-World Examples
Master KEDA implementation on Amazon EKS with comprehensive examples for multiple scaling scenari...
Related Tools & Projects
BG Deployer
Automated blue-green deployment for zero-downtime AWS releases
mCert
SSL certificate monitoring with Slack/email alerts & Telegram
mTracker
Real-time Linux user activity monitoring with Slack notifications
mWatcher
Server health monitoring for CPU, memory, disk with alerting
gCrypt
Git-crypt wrapper for secure file encryption & access management
Interactive Tools
AWS VPC Designer, EKS Cost Calculator, and more utilities
External Resources
Quick Actions
Found this helpful?
Help us improve this documentation by sharing your feedback or suggesting improvements.