cs.oldnet

All sheets / CI/CD & Release

Jenkins

Declarative pipeline syntax and Jenkins architecture.

Declarative Jenkinsfile

pipeline {
  agent { label 'linux' }
  options {
    timeout(time: 30, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '20'))
    disableConcurrentBuilds()
  }
  environment { APP = 'web'; CREDS = credentials('aws-creds') }
  parameters { choice(name: 'ENV', choices: ['dev', 'staging', 'prod']) }
  triggers { pollSCM('H/5 * * * *') }
  stages {
    stage('Build') { steps { sh 'npm ci && npm run build' } }
    stage('Test') {
      parallel {
        stage('Unit') { steps { sh 'npm test' } }
        stage('Lint') { steps { sh 'npm run lint' } }
      }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps {
        input message: "Deploy to ${params.ENV}?"
        sh "./deploy.sh ${params.ENV}"
      }
    }
  }
  post {
    always { junit 'reports/*.xml'; archiveArtifacts 'dist/**' }
    failure { slackSend channel: '#builds', message: "Failed: ${env.BUILD_URL}" }
  }
}

Agents

agent any
agent none                         // set per stage
agent { docker { image 'node:22' } }
agent { kubernetes { yamlFile 'pod.yaml' } }

Controller schedules and stores config; agents (nodes) run builds. Don't run builds on the controller.

when conditions

when { branch 'main' }
when { tag 'v*' }
when { changeRequest() }                 // PR builds
when { expression { params.ENV == 'prod' } }
when { allOf { branch 'main'; not { changeset '**/*.md' } } }

Credentials

withCredentials([usernamePassword(credentialsId: 'docker', usernameVariable: 'U', passwordVariable: 'P')]) {
  sh 'echo $P | docker login -u $U --password-stdin'   // single quotes: no Groovy interpolation of secrets
}
withCredentials([string(credentialsId: 'token', variable: 'TOKEN')]) { sh './call.sh' }

Scripted & shared libraries

// scripted pipeline: plain Groovy, more flexible
node('linux') {
  stage('Build') { checkout scm; sh 'make' }
}

// shared library: vars/deployApp.groovy
def call(String env) { sh "./deploy.sh ${env}" }
// Jenkinsfile
@Library('ci-lib') _
deployApp('staging')

Job types

TypeUse
Freestylesimple UI-configured jobs (legacy)
Pipelinesingle Jenkinsfile job
Multibranch Pipelineauto-creates a job per branch/PR with a Jenkinsfile
Organization folderscans a whole GitHub org

Useful env vars

BUILD_NUMBER, BUILD_URL, JOB_NAME, BRANCH_NAME, CHANGE_ID (PR), GIT_COMMIT, WORKSPACE.

Jenkins vs GitHub Actions

JenkinsGitHub Actions
Hostingself-managed controller + agentsSaaS runners or self-hosted
ConfigGroovy JenkinsfileYAML workflows
Extensibility1800+ plugins (upgrade pain)Marketplace actions
Best forcomplex on-prem, custom hardwareGitHub-native, low ops

Best practices

  • Pipeline as code, in the repo; shared libraries for common steps.
  • Ephemeral agents (Docker/K8s) for clean, reproducible builds.
  • Keep plugins minimal and updated; back up JENKINS_HOME.
  • Fail fast: lint/unit before slow stages; use parallel.