# Jenkins Declarative Pipeline
## source
* https://digitalvarys.com/jenkins-declarative-pipeline-with-examples/
* https://www.lambdatest.com/blog/jenkins-declarative-pipeline-examples/
* https://www.youtube.com/watch?v=7KCS70sCoK0&t=1651s
## Required fields of jenkinsfile
```groovy
pipeline {
agent any
stages {
stage('Hello World Stage') {
steps {
echo 'Hello World '
}
}
}
}
```
## jenkinsfile stages
```groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'building the application'
}
}
stage('test') {
steps {
echo 'testing the application'
}
}
stage('deploy') {
steps {
echo 'deploying the application'
}
}
}
}
```
## jenkinsfile post after stages
```groovy
pipeline {
agent any
stages {
stage('Hello World Stage') {
steps {
echo 'Hello World '
}
}
}
post {
always {
echo 'always'
}
success {
echo 'success'
}
failure {
echo 'failure'
}
}
}
```
## when condition for stages
```groovy
CODE_CHANGES = getGitChanges()
pipeline {
agent any
stages {
stage('Build') {
when {
expression {
BRANCH_NAME == 'dev' && CODE_CHANGES == true
}
}
steps {
echo 'building the application'
}
}
stage('test') {
when {
expression {
BRANCH_NAME == 'dev' || BRANCH_NAME == 'master'
}
}
steps {
echo 'testing the application'
}
}
stage('deploy') {
steps {
echo 'deploying the application'
}
}
}
}
```
## jenkinsfile environment variable
```groovy
pipeline {
agent any
environment {
NEW_VERSION = '1.3.0'
SERVER_CREDENTIALS = credentials('server-credentials')
}
stages {
stage('Build') {
steps {
echo 'building the application'
echo "building version ${NEW_VERSION}"
}
}
stage('test') {
steps {
echo 'testing the application'
}
}
stage('deploy') {
steps {
echo 'deploying the application'
echo "deploying with ${SERVER_CREDENTIALS}"
}
}
}
}
```
## withCredentials in jenkinsfile
```groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'building the application'
}
}
stage('test') {
steps {
echo 'testing the application'
}
}
stage('deploy') {
steps {
echo 'deploying the application'
withCredentials([
usernamePassword(credentials: 'server-credentials', usernameVariable: USER, passwordVariable: PWD)
]) {
sh "some script ${USER} ${PWD}"
}
}
}
}
}
```
## tools in jenkinsfile
```groovy
pipeline {
agent any
tools {
maven 'Maven'
gradle 'Gradle'
jdk 'JDK'
}
stages {
stage('Hello World Stage') {
steps {
echo 'Hello World'
sh "mvn install"
}
}
}
}
```
## Referring Env Variables from Jenkins env-vars.html
```groovy
pipeline {
agent any
stages {
stage('Initialization') {
steps {
echo "${env.JOB_NAME}"
}
}
}
}
```
## Creating & Referring Environment variable in Jenkinsfile
```groovy
pipeline {
agent any
environment {
DEPLOY_TO = 'production'
}
stages {
stage('Initialization') {
steps {
echo "${DEPLOY_TO}"
}
}
}
}
```
## Initialize Env variables using sh commands
```groovy
pipeline {
agent any
stages {
stage('Initialization') {
environment {
JOB_TIME = sh (returnStdout: true, script: "date '+%A %W %Y %X'").trim()
}
steps {
sh 'echo $JOB_TIME'
}
}
}
}
```
## Loading credentials in declarative pipeline
```groovy
pipeline {
agent any
environment {
MY_CRED = credentials('MY_SECRET')
}
stages {
stage('Load Credentials') {
steps {
echo "Username is $MY_CRED_USR"
echo "Password is $MY_CRED_PSW"
}
}
}
}
```
## Simple when block
```groovy
pipeline {
agent any
stages {
stage('build') {
when {
branch 'dev'
}
steps {
echo "Working on dev branch"
}
}
}
}
```
## when block using Groovy expression
```groovy
pipeline {
agent any
stages {
stage('build') {
when {
expression {
return env.BRANCH_NAME == 'dev';
}
}
steps {
echo "Working on dev branch"
}
}
}
}
```
## when block with environment variables
```groovy
pipeline {
agent any
environment {
DEPLOY_TO = 'production'
}
stages {
stage('Welcome Step') {
when {
environment name: 'DEPLOY_TO', value: 'production'
}
steps {
echo 'Hello World'
}
}
}
}
```
## when block with multiple conditions & all conditions should be satisfied
```groovy
pipeline {
agent any
environment {
DEPLOY_TO = 'production'
}
stages {
stage('Welcome Step') {
when {
allOf {
branch 'master';
environment name: 'DEPLOY_TO', value: 'production'
}
}
steps {
echo 'Welcome to LambdaTest'
}
}
}
}
```
## when block with multiple conditions & any of the given conditions should be satisfied
```groovy
pipeline {
agent any
environment {
DEPLOY_TO = 'production'
}
stages {
stage('Welcome Step') {
when {
anyOf {
branch 'master';
environment name: 'DEPLOY_TO', value: 'production'
}
}
steps {
echo 'Welcome to LambdaTest'
}
}
}
}
```
## Loading maven using tools
```groovy
pipeline {
agent any
tools {
maven 'Maven 3.6.3'
}
stages {
stage('Load Tools') {
steps {
sh "mvn -version"
}
}
}
}
```
## post with multiple conditional blocks
```groovy
pipeline {
agent any
stages {
stage('build step') {
steps {
echo "Build stage is running"
}
}
}
post {
always {
echo "You can always see me"
}
success {
echo "I am running because the job ran successfully"
}
unstable {
echo "Gear up ! The build is unstable. Try fix it"
}
failure {
echo "OMG ! The build failed"
}
}
}
```
## triggers sample
```groovy
pipeline {
agent any
triggers {
cron('* * * * *')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
```
## Mark build as UNSTABLE based on Code Coverage
```groovy
pipeline {
agent any
tools {
maven 'MAVEN_PATH'
jdk 'jdk8'
}
stages {
stage("Tools initialization") {
steps {
sh "mvn --version"
sh "java -version"
}
}
stage("Checkout Code") {
steps {
git branch: 'master',
url: "https://github.com/iamvickyav/spring-boot-data-H2-embedded.git"
}
}
stage("Building Application") {
steps {
sh "mvn clean package"
}
}
stage("Code coverage") {
steps {
jacoco(
execPattern: '**/target/**.exec',
classPattern: '**/target/classes',
sourcePattern: '**/src',
inclusionPattern: 'com/iamvickyav/**',
changeBuildStatus: true,
minimumInstructionCoverage: '30',
maximumInstructionCoverage: '80')
}
}
}
}
```
## Input (Defined at stage level)
```groovy
pipeline {
agent any
stages {
stage('Example') {
input {
message "Can we Proceed?"
ok "Yes"
submitter "Digital Varys"
parameters {
string(name: 'PERSON', defaultValue: 'DigiralVarys', description: 'Member')
}
}
steps {
echo "${PERSON}, is proceeding..."
}
}
}
}
```
## options (Defined at stage or pipeline level)
disableConcurrentBuilds, newContainerPerStage, preserveStashes, quietPeriod, retry, skipDefaultCheckout, skipStagesAfterUnstable, timeout
```groovy
pipeline {
agent any
options {
timeout(time: 30, unit: 'MINUTES')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
```
## When
Branch, buildingTag, changelog, changeset, changeRequest, environment, equals, expression, tag, not, allOf, anyOf, triggeredBy
```groovy
pipeline {
agent any
stages {
stage('Example Build') {
when {
anyOf {
branch 'master'; branch 'staging'
}
}
steps {
echo 'Hello World'
}
}
stage('Example Deploy') {
when {
branch 'production'
}
steps {
echo 'Deploying'
}
}
}
}
```
## Parallel
```groovy
pipeline {
agent any
stages {
stage('NORMAL Stage') {
steps {
echo 'I am one'
}
}
stage('Parallel Stage') {
when {
branch 'master'
}
failFast true
parallel {
stage('stage one') {
agent {
label "stageonebranch"
}
steps {
echo "Me in stage one"
}
}
stage('Stage two') {
agent {
label "stage two"
}
steps {
echo "Me in stage two"
}
}
stage('Stage three') {
agent {
label "Stage Three"
}
}
}
}
}
}
```
## Parameters
```groovy
pipeline {
agent any
parameters {
string(name: 'yyyyy', defaultValue: 'XXX', description: 'Hello world')
text(name: 'Demo', defaultValue: '', description: 'Demo parameter')
booleanParam(name: 'Boolean', defaultValue: true, description: 'Boolean value')
choice(name: 'CHOICE', choices: ['A', 'B', 'C'], description: 'Choose one')
password(name: 'PASSWORD', defaultValue: 'Key', description: 'Enter a password')
file(name: "FILE", description: "file to upload")
}
stages {
stage('Example') {
steps {
echo "Hello ${params.yyyyy}"
echo "Biography: ${params.Demo}"
echo "Toggle: ${params.Boolean }"
echo "Choice: ${params.CHOICE}"
echo "Password: ${params.PASSWORD}"
}
}
}
}
```
## Post
Always, Changed, Fixed, Regression, Aborted, Failure, Success, Unstable, Unsuccessful, cleanup
```groovy
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
post {
always {
echo 'Running after the stages'
}
}
}
```
## Triggers
Cron, pollSCM, upstream
```groovy
pipeline {
agent any
triggers {
cron('H */4 * * 1-5')
}
stages {
stage('Example') {
steps {
echo 'Hello World'
}
}
}
}
```
## script block helps us run Groovy code inside the Jenkins declarative pipeline.
```groovy
pipeline {
agent any
parameters {
string(name: 'NAME', description: 'Please tell me your name')
choice(name: 'GENDER', choices: ['Male', 'Female'], description: 'Choose Gender')
}
stages {
stage('Printing name') {
steps {
script {
def name = "${params.NAME}"
def gender = "${params.GENDER}"
if(gender == "Male") {
echo "Mr. $name"
} else {
echo "Mrs. $name"
}
}
}
}
}
}
```