Home Portfolio Blog Courses

Best Practices Guide - Jenkins as Code

Recommended practices for using Jenkins as Code automation framework

Updated Jan 15, 2024
8 min read
Intermediate
tools

Best Practices Guide

Recommended practices for using Jenkins as Code automation framework

πŸ“š Related Guides:

πŸ“‹ Table of Contents

βš™οΈ 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

βœ… 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

🧭 Navigation

Related Topics:


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

Found this helpful?

Help us improve this documentation by sharing your feedback or suggesting improvements.