Table of Contents
Why should you use a Jenkinsfile?
The biggest advantage of a Jenkinsfile is the ability to use version control to manage your build system.
When you use freestyle jobs you can loose you configuration due to limit history depth.
Descriptive vs Scripted
Jenkinsfiles come in two flavours:
Declarative pipelines always begin with the word pipeline
Scripted pipelines always begin with the word node
This tutorial deals with the declarative pipeline scripts.
Prerequisites
Before you can use a Jenkinsfile-Job you need to install this plugin in your Jenkins:
https://plugins.jenkins.io/workflow-aggregator/
A minimalistic Jenkinsfile
pipeline { agent any environment{ } stages { stage('Build') { steps { echo 'Building..' } } stage('Test') { steps { echo 'Testing..' } } stage('Deploy') { steps { echo 'Deploying....' } } } }
Agent
The agent defines on which build node the project can be build.
agent any
‘any’ means that the job can be run on every available node on your Jenkins master. You can of course tie a job to a certain node e.g. by label
agent { label 'windows'}
Environment
The environment block can be used to set environment variables e.g. path to git executable, special directories for reports.
environment{ NEW_VERSION = '1.3.0' }
Stages & Steps
You can divide your pipeline script into several logical units called stages.
e.g. Build – Test – Deploy
You can add additional stages for linting, quality checking, code coverage and so on.
The steps is where the magic happens. A stage can consist of several steps
Conditions
stage('Deploy') {
when { expression { BRANCH_NAME == 'main' } }
steps { echo 'Deploying....' } }
You can apply a when block to tie some stages to a specific preconditions. In this example we only want to deploy our project when we are dealing with the main branch.
Parallel execution
If you want to execute tests in parallel you do the following:
stage('Test') { parallel { stage('Test On Windows') { agent { label "windows" } steps { bat "run-tests.bat" } } stage('Test On Linux') { agent { label "linux" } steps { sh "run-tests.sh" } } } }
Post actions
post { always { } failure { } }
Available Environment Variables
https://<your_jenkins_ip_orcname>/env-vars.html
e.g. https://localhost:8080/env-vars.html
IDE / Tool Support
If you want IDEA to recognize a Jenkinsfile as a Groovy file, then you can add the String “Jenkinsfile” as a valid file name pattern (normally contains file endings) for Groovy files. This is supported “out of the box” without requiring any additional Plugin (except the “Groovy” Plugin, but that is already part of IDEA).
Another solution for PyCharm:
The following filetype xml will highlight Jenkinsfile syntax in PyCharm
Another way is to use the Pipeline Editor Plugin