Back Home

Jenkins

Jenkins Pipeline

Jenkins Groovy Pipeline

There is a groovy flavour of the pipeline that follows the 'declarative' approach that confiuration as an artifact checked into in git

Jenkins then

  • visually shows each 'stage' as well as the progress and logs of each stage
  • individual decisions can be made based on the the result of each stage
  • stages can be run in parallel
  • supports timouts, triggers and cron jobs
  • conditions (when clause)
  • create and reuse functions
  • exception handling
  • record results and
  • send notifcations

A minimal groovy pipeline might look like:

stages {
  stage('Build') {
    steps {
      sh 'echo "This is my first step"'
    }
  }
  stage('Test') {
    steps
      sh 'echo "This is my Test step"'
    }
  }
  stage('Deploy') {
    steps {
      sh 'echo "This is my Deploy step"'
    }
  }
}

Minimal Maven Build

pipeline {
    agent any
    tools {
        maven 'Maven 3.3.9'
        jdk 'jdk8'
    }
    stages {
        stage ('Initialize') {
            steps {
                sh '''
                    echo "PATH = ${PATH}"
                    echo "M2_HOME = ${M2_HOME}"
                '''
            }
        }
 
        stage ('Build') {
            steps {
                sh 'mvn -Dmaven.test.failure.ignore=true install' 
            }
            post {
                success {
                    junit 'target/surefire-reports/**/*.xml' 
                }
            }
        }
    }
}

Building a Pipeline the Basic Steps

A Jenkins groovy pipeline consists of a number of standard modules, including:

  • stages - We have multiple stages in our build in which each stage section has a different steps. Stages are what appears on the Jenkins dashboard.
  • steps - each stage can have multiple steps
    • steps can have timeouts and retries
    • steps can be run in parallel
stages {
  stage('Build') {
    steps {
      sh 'echo "Step 1"'
      sh 'echo "Step 2"'
      sh 'echo "Step 3"'
    }
  }
}

Basic Steps

Timeouts and retries

pipeline {
  agent any
  stages {
    stage('Dev Deployment') {
      steps {
        retry(x) { // It Retries x number of times mentioned until its successful
          sh './dev-deploy.sh'
        }
        timeout(time: x, unit: 'MINUTES') { // Time out option will make the step wait for x mins to execute if it takes more than that it will fail
          sh './readiness-check.sh'
        }
      }
    }
  }
}

Steps

Parallel Stages

Multiple steps in a single parallel can also be executed in parallel.

stage("Parallel") {
  steps {
    parallel (
      "Taskone" : {
        //do some stuff
      },
      "Tasktwo" : {
        // Do some other stuff in parallel
      }
    )
  }
}

Post Build Actions

A post build action can have a number of standard functions:

pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        sh 'echo "Fail!"; exit 1'
      }
    }
  }
  post {
    always {
      echo 'always runs regardless of the completion status of the Pipeline run'
    }
    success {
      echo 'step will run only if the build is successful'
    }
    failure {
      echo 'only when the Pipeline is currently in a "failed" state run, usually expressed in the Web UI with the red indicator.'
    }
    unstable {
      echo 'current Pipeline has "unstable" state, usually by a failed test, code violations and other causes, in order to run. Usually represented in a web UI with a yellow indication.'
    }
    changed {
      echo 'can only be run if the current Pipeline is running at a different state than the previously completed Pipeline'
    }
  }
}

Global or Stage - Environment Variables

Environment variables can be set

  • globally,
  • or per stage - in which they only have stage scope
pipeline {
  agent any
 
  environment {
    USE_JDK = 'true'
    JDK ='c:/Java/jdk1.8'
  }
 
  stages {
    stage('Build') {
      steps {
        sh 'printenv'
      }
    }
  }
}

Exception Handling

For exception handling you can now use the try catch block in order to execute the step and catch exceptions.

node {
  stage('SampleTryCatch') {
    try {
      sh 'exit 1'
    }
    catch (exc) {
      echo 'Something didn't work and got some exceptions'
      throw
    }
  }
}

Sending Notifications

When the pipeline succeeds or fails the current status notification needs to be sent to the concerned team. We can add some notification or other steps in the pipeline to perform finalization, notification, or other end-of-pipeline tasks.

Email notification:

post {
  failure {
    mail to: 'team@test.com',
      subject: "Pipeline has failed: ${currentBuild.fullDisplayName}",
      body: "Error in ${env.BUILD_URL}"
  }
}

Slack notification:

post {
  success {
    slackSend channel: '#Devops-team',
      color: 'green',
      message: "The pipeline ${currentBuild.fullDisplayName} completed successfully."
}

Manual Input Steps - Locking and Milestones

the Input Plugin supports a number of means to provide manual input from

  • input fields
  • drop downs
  • yes/no button confirmations
// Input Step
timeout(time: 15, unit: "MINUTES") {
    input message: 'Do you want to approve the deploy in production?', ok: 'Yes'
}

Milestone and Lock

The lock step (from the lockable-resources plugin) allows to lock some specified resource so that only a single pipeline execution can enter this stage simultaneously (you don't want to run two deployments simultaneously, don't you?)

The milestone step (from the pipeline-milestone-step plugin) will abort any older pipeline executions, if a more recent commit already reached the milestone (you don't want to let an older commit that hangs longer in CI overwrite the deployment of a newer commit, don't you?).

stage('Deploy') {
  input "Deploy?"
  milestone()
  lock('Deployment') {
    node {
      echo "Deploying"
    }
  }
}

Reuseable Libaries

Groovy code libaries can be added in two ways:

  • libaries can be defined via the Jenkins groovy

  • groovy type @Grab
@Library('somelib')
import com.mycorp.pipeline.somelib.UsefulClass
 
java_build_tools.txt · Last modified: 2019/11/29 05:55 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd