How to write a Jenkinsfile?
· Category: DevOps & CI/CD
Short answer
A Jenkinsfile is a text file containing the definition of a Jenkins pipeline. It can be written in declarative or scripted syntax and is stored in version control alongside application code.
Steps
- Create a file named
Jenkinsfilein the repository root. - Define the
pipelineblock. - Specify the
agent. - Add
stagesandsteps. - Configure post-build actions.
Example
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Build') {
steps {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
}
post {
always {
junit 'reports/**/*.xml'
}
}
}
Tips
- Use declarative pipelines for standard workflows.
- Use scripted pipelines only when you need advanced logic.
- Validate Jenkinsfile syntax with the Jenkins linter.
Common issues
- Missing
agentcauses the pipeline to fail. - Shell commands behave differently on Windows and Linux agents.
- Credentials must be referenced with
withCredentials.