Jenkins Commands
Jenkins is an open-source automation server for building, testing, and deploying software.
Installation
Docker
# Run Jenkins
docker run -d -p 8080:8080 -p 50000:50000 jenkins/jenkins:lts
# Volume mount for persistence
docker run -d -p 8080:8080 -p 50000:50000 \
-v jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts
Linux
# Add Jenkins repo (Ubuntu)
curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc > /dev/null
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null
# Install
sudo apt-get update
sudo apt-get install jenkins
# Start Jenkins
sudo systemctl start jenkins
sudo systemctl enable jenkins
Jenkins CLI
| Command | Description |
|---|---|
java -jar jenkins-cli.jar -s http://localhost:8080 help | Show available commands |
java -jar jenkins-cli.jar -s http://localhost:8080 list-jobs | List all jobs |
java -jar jenkins-cli.jar -s http://localhost:8080 get-job JOBNAME | Get job details |
java -jar jenkins-cli.jar -s http://localhost:8080 build JOBNAME | Trigger job |
java -jar jenkins-cli.jar -s http://localhost:8080 console JOBNAME | View job output |
Basic Job Creation (Declarative Pipeline)
Simple Pipeline
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
stage('Deploy') {
steps {
sh './deploy.sh'
}
}
}
post {
always {
cleanWs()
}
success {
echo 'Pipeline succeeded!'
}
failure {
echo 'Pipeline failed!'
}
}
}
Common Jenkinsfile Patterns
Declarative with Parameters
pipeline {
agent any
parameters {
string(name: 'ENVIRONMENT', defaultValue: 'dev', description: 'Deployment environment')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests')
choice(name: 'LOG_LEVEL', choices: ['INFO', 'DEBUG', 'ERROR'], description: 'Log level')
}
environment {
CI = 'true'
NODE_ENV = "${params.ENVIRONMENT}"
}
stages {
stage('Setup') {
steps {
echo "Deploying to ${params.ENVIRONMENT}"
}
}
stage('Test') {
when {
expression { params.RUN_TESTS == true }
}
steps {
sh 'npm test'
}
}
}
}
Matrix Build (Multi-Config)
pipeline {
agent any
options {
timestamps()
timeout(time: 1, unit: 'HOURS')
}
stages {
stage('Build Matrix') {
matrix {
agent any
axes {
axis {
name: 'NODEJS_VERSION'
values: '14.x', '16.x', '18.x'
}
axis {
name: 'OS'
values: 'linux', 'windows', 'macos'
}
}
stages {
stage('Build') {
steps {
echo "Building on ${OS} with Node ${NODEJS_VERSION}"
sh 'npm install && npm run build'
}
}
}
}
}
}
}
Scripted Pipeline
node {
try {
stage('Checkout') {
checkout scm
}
stage('Build') {
sh 'npm install'
def buildResult = sh(script: 'npm run build', returnStatus: true)
if (buildResult != 0) {
error('Build failed')
}
}
stage('Test') {
sh 'npm test'
}
stage('Deploy') {
if (env.BRANCH_NAME == 'main') {
sh './deploy-prod.sh'
} else {
sh './deploy-staging.sh'
}
}
} catch (Exception e) {
currentBuild.result = 'FAILURE'
echo "Pipeline failed: ${e.message}"
throw e
}
}
Step Examples
Parallel Execution
pipeline {
agent any
stages {
stage('Tests') {
parallel {
stage('Unit Tests') {
steps {
sh 'npm run test:unit'
}
}
stage('Integration Tests') {
steps {
sh 'npm run test:integration'
}
}
stage('E2E Tests') {
steps {
sh 'npm run test:e2e'
}
}
}
}
}
}
Conditional Execution
pipeline {
agent any
stages {
stage('Deploy') {
when {
branch 'main'
environment name: 'BUILD_TYPE', value: 'RELEASE'
}
steps {
sh './deploy-prod.sh'
}
}
stage('Stage Deploy') {
when {
not { branch 'main' }
}
steps {
sh './deploy-staging.sh'
}
}
}
}
Artifact Handling
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm run build'
}
}
}
post {
always {
// Archive artifacts
archiveArtifacts artifacts: 'dist/**/*', allowEmptyArchive: true
// Publish test results
junit 'test-results/**/*.xml'
// Code coverage
publishHTML([
reportDir: 'coverage',
reportFiles: 'index.html',
reportName: 'Coverage Report'
])
}
}
}
Notifications
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm run build'
}
}
}
post {
failure {
emailext(
subject: "Build failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: '''${SCRIPT, template="groovy-html.template"}''',
recipientProviders: [
developers(),
requestor()
]
)
}
success {
// Slack notification
slackSend(
channel: '#deployments',
message: "Build ${env.BUILD_NUMBER} deployed successfully"
)
}
}
}
Environment Variables
Global Variables
| Variable | Description |
|---|---|
BUILD_NUMBER | Current build number |
BUILD_ID | Current build ID |
JOB_NAME | Name of the job |
WORKSPACE | Workspace directory |
GIT_COMMIT | Git commit hash |
GIT_BRANCH | Git branch name |
BRANCH_NAME | Branch name (multi-branch) |
Custom Environment
pipeline {
agent any
environment {
REGISTRY = 'docker.io'
IMAGE_NAME = 'my-app'
IMAGE_TAG = "${BUILD_NUMBER}"
SLACK_CHANNEL = '#deployments'
}
stages {
stage('Build') {
steps {
sh 'echo "Building ${IMAGE_NAME}:${IMAGE_TAG}"'
}
}
}
}
Git Integration
pipeline {
agent any
stages {
stage('Checkout') {
steps {
// Standard checkout
checkout scm
// Specific repository
checkout([
$class: 'GitSCM',
branches: [[name: '*/main']],
userRemoteConfigs: [[url: 'https://github.com/user/repo.git']]
])
}
}
stage('Get Commit Info') {
steps {
script {
env.GIT_HASH = sh(
script: "git rev-parse --short HEAD",
returnStdout: true
).trim()
echo "Commit: ${env.GIT_HASH}"
}
}
}
}
}
Docker Integration
pipeline {
agent any
stages {
stage('Build Docker Image') {
steps {
script {
docker.build("${IMAGE_NAME}:${IMAGE_TAG}")
}
}
}
stage('Push to Registry') {
steps {
script {
docker.withRegistry("https://${REGISTRY}", 'docker-credentials') {
docker.image("${IMAGE_NAME}:${IMAGE_TAG}").push()
docker.image("${IMAGE_NAME}:${IMAGE_TAG}").push('latest')
}
}
}
}
stage('Run Tests in Container') {
steps {
script {
docker.image("${IMAGE_NAME}:${IMAGE_TAG}").inside {
sh 'npm test'
}
}
}
}
}
}
Credentials Management
pipeline {
agent any
environment {
// Use credentials plugin
DOCKER_CREDS = credentials('docker-credentials')
API_KEY = credentials('api-key')
}
stages {
stage('Deploy') {
steps {
script {
withCredentials([
usernamePassword(credentialsId: 'github-credentials', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')
]) {
sh '''
git config --global credential.helper store
echo "https://${GIT_USER}:${GIT_PASS}@github.com" > ~/.git-credentials
'''
}
}
}
}
}
}
Error Handling
pipeline {
agent any
options {
timeout(time: 30, unit: 'MINUTES')
timestamps()
}
stages {
stage('Build') {
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
sh 'npm run build'
}
}
}
}
post {
always {
// Cleanup
cleanWs()
}
unstable {
echo 'Build is unstable'
}
failure {
echo 'Build failed'
sh 'make rollback || true'
}
}
}
HTTP Requests
pipeline {
agent any
stages {
stage('Health Check') {
steps {
script {
def response = httpRequest url: 'https://api.example.com/health', httpMode: 'GET'
echo "Response: ${response.status}"
}
}
}
stage('Trigger External Job') {
steps {
httpRequest(
url: 'https://jenkins.example.com/job/downstream/build',
httpMode: 'POST',
authentication: 'jenkins-credentials'
)
}
}
}
}
Shared Libraries
// vars/greeting.groovy
def call(String name) {
echo "Hello, ${name}!"
}
// Jenkinsfile
@Library('my-library') _
pipeline {
agent any
stages {
stage('Hello') {
steps {
greeting('John')
}
}
}
}
Best Practices
- Keep pipelines DRY with shared libraries
- Use parameters for flexibility
- Implement proper error handling
- Log meaningful messages
- Test pipelines in sandbox
- Use credentials plugin for sensitive data
- Set appropriate timeouts
- Clean up workspace
- Version control Jenkinsfiles
- Monitor pipeline performance
Resources
Last updated: 2026-03-30|Jenkins 2.4+