Answer
Jenkinsfile: Declarative vs Scripted Pipeline
A Jenkinsfile is a text file that defines your Jenkins pipeline as code and lives in your repository root. This enables Pipeline-as-Code: version-controlled, peer-reviewed CI/CD.
Declarative Pipeline (Recommended)
Structured, opinionated syntax with pipeline {} block.
GROOVY
pipeline {
// Where to run: any available agent/node
agent any
// Environment variables
environment {
APP_ENV = 'staging'
MAVEN_OPTS = '-Xmx512m'
}
// Optional: tools to auto-install
tools {
maven 'Maven-3.9'
jdk 'JDK-17'
}
stages {
stage('Checkout') {
steps {
checkout scm // checks out the branch that triggered the build
}
}
stage('Build') {
steps {
sh 'mvn clean package -DskipTests'
}
}
stage('Run Automation Tests') {
steps {
sh 'mvn test -Dbrowser=chrome -Denv=${APP_ENV}'
}
post {
always {
// Publish JUnit test results
junit 'target/surefire-reports/*.xml'
// Publish HTML report
publishHTML([
reportDir: 'target/extent-reports',
reportFiles: 'index.html',
reportName: 'Test Report',
])
}
}
}
stage('Deploy') {
when {
branch 'main' // only deploy on main branch
expression { currentBuild.result == null || currentBuild.result == 'SUCCESS' }
}
steps {
sh './deploy.sh ${APP_ENV}'
}
}
}
post {
success { echo 'All stages passed!' }
failure {
mail(
to: 'qa-team@company.com',
subject: "BUILD FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: "Check: ${env.BUILD_URL}"
)
}
always {
cleanWs() // clean workspace after every build
}
}
}
Scripted Pipeline (Groovy — More Flexible)
Full Groovy code inside node {} block — no structural constraints.
GROOVY
node {
def mavenHome = tool 'Maven-3.9'
stage('Checkout') {
checkout scm
}
stage('Build') {
sh "${mavenHome}/bin/mvn clean package"
}
stage('Test') {
try {
sh "${mavenHome}/bin/mvn test"
} catch (Exception e) {
currentBuild.result = 'UNSTABLE'
echo "Tests failed: ${e.message}"
} finally {
junit 'target/surefire-reports/*.xml'
}
}
if (env.BRANCH_NAME == 'main') {
stage('Deploy') {
sh './deploy.sh'
}
}
}
Key Differences
| Feature | Declarative | Scripted |
|---|---|---|
| Syntax | Structured DSL | Full Groovy |
| Learning curve | Easy | Harder |
| Error checking | Upfront validation | Runtime only |
| Flexibility | Limited | Full |
| Recommended | Yes | Legacy/complex only |
post {} section | Built-in | Manual try/finally |
