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' }Job types
| Type | Use |
|---|---|
| Freestyle | simple UI-configured jobs (legacy) |
| Pipeline | single Jenkinsfile job |
| Multibranch Pipeline | auto-creates a job per branch/PR with a Jenkinsfile |
| Organization folder | scans 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
| Jenkins | GitHub Actions | |
|---|---|---|
| Hosting | self-managed controller + agents | SaaS runners or self-hosted |
| Config | Groovy Jenkinsfile | YAML workflows |
| Extensibility | 1800+ plugins (upgrade pain) | Marketplace actions |
| Best for | complex on-prem, custom hardware | GitHub-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.