Jenkins is an automation server. It allows for all kinds of automations. It is primarily used for Build automation, Continuous Integration, and Continuous Deployment.

  1. Install Jenkins on Ubuntu
  2. Jenkins Pipeline - Hello World
  3. Jenkins Pipeline: running external programs with sh or bat
  4. Jenkins Pipeline: Send e-mail notifications
  5. Jenkins Pipeline: Add some text to the job using shortText
  6. Jenkins CLI: create node
  7. Triggers from Version Control Systems
  8. Report failures.
  9. Send alerts
  10. Collect test coverage data.
  11. Jenkins slides

How to set environment variables in Jenkins?

A section called environment can be added to the pipeline

environment {
    SOME_NAME = "some value"
}

pipeline {
   agent none
   environment {
       field = 'some'
   }
   stages {
       stage ('Preparation') {
           agent { label 'master'}
           environment {
               JENKINS_PATH = sh(script: 'pwd', , returnStdout: true).trim()
           }
           steps {
               echo "Hello world"
               echo "PATH=${JENKINS_PATH}"
               sh 'echo "JP=$JENKINS_PATH"'
          }
      }
   }
}

How to use environment variables in the environment section of Jenkins?

         environment {
               PATH = "/path/to/dir:${env.PATH}"
               JNK_PATH = "${env.WORKSPACE}\\subdir"
           }

The above only works when the environment section is inside a "stage" but would yield "null" for WORKSPACE outside the stages.

Set environment executing code

environment {
    field = func()
}

def func() {
    ...
    return "value"
}

Add badges

   manager.addBadge("error.gif", "Failed build")

Run external code, capture output

script {
      v = sh(script: 'echo " 42"; echo', returnStdout: true).trim()
      echo v
      echo "a${v}b"
}

bat for windows.

catch and print error in jenkins

pipeline {
   agent none
   stages {
       stage ('Catch crash') {
           agent { label 'master'}
           steps {
               echo "before crash"
               script {
                   try {
                       sh 'exit 1'
                   } catch (err) {
                       echo "exception caught, going on"
                       println err // java.lang.ClassCastException:
org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received
class hudson.AbortException
                   }
               }
               echo "after crash"
           }
       }
       stage ('Continue after crash') {
           agent { label 'master'}
           steps {
               echo "stage after crash"
           }
       }
   }
}

dir and tmp are problematic

  stages {
       stage ('Run external exe') {
           agent { label 'master'}
           steps {
               sh 'pwd'
               dir('/tmp/gabor') {
                   echo "inside"
                   sh 'pwd'
                   //sh 'sudo ./do-something.py'
               }
               sh 'pwd'
               //sh "sudo sh -c 'cd /tmp; ./do-something.py; cd -'"
           }
       }

java.io.IOException: Failed to mkdirs: /tmp@tmp/durable-e569697c
        at hudson.FilePath.mkdirs(FilePath.java:1170)
        at
org.jenkinsci.plugins.durabletask.FileMonitoringTask$FileMonitoringController.<init>(FileMonitori
ngTask.java:156)
        at
org.jenkinsci.plugins.durabletask.BourneShellScript$ShellController.<init>(BourneShellScript.java
:198)
        at
org.jenkinsci.plugins.durabletask.BourneShellScript$ShellController.<init>(BourneShellScript.java
:190)
        at
org.jenkinsci.plugins.durabletask.BourneShellScript.launchWithCookie(BourneShellScript.java:111)
        at
org.jenkinsci.plugins.durabletask.FileMonitoringTask.launch(FileMonitoringTask.java:86)
        at
org.jenkinsci.plugins.workflow.steps.durable_task.DurableTaskStep$Execution.start(DurableTaskStep
.java:182)
        at org.jenkinsci.plugins.workflow.cps.DSL.invokeStep(DSL.java:229)
        at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:153)
        at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
        at sun.reflect.GeneratedMethodAccessor1989.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
        at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:157)
        at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
        at
org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterc
eptor.java:133)
        at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:155)
        at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:159)
        at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:129)
        at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:129)
        at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
        at WorkflowScript.run(WorkflowScript:16)

Jenkins / Groovy - define functions and call them with parameters

def report(status) {
   println "status=${status}"
}

and call them

report("text")

BUILD USER

Need the Build User Vars Plugin and then write the following code:

pipeline {
   agent { label 'master' }
   stages {
       stage('build') {
           steps {
               wrap([$class: 'BuildUser']) {
                   echo BUILD_USER
                   echo BUILD_USER_ID
                   echo BUILD_USER_FIRST_NAME
                   echo BUILD_USER_LAST_NAME
               }
               script {
                   wrap([$class: 'BuildUser']) {
                       build_user_id = BUILD_USER_ID
                   }
               }
               echo build_user_id
           }
       }
   }
}

Environment variables on Linux

sh 'printenv'
sh 'env'

Input during the process

pipeline {
   agent { label 'master' }
   stages {
       stage('build') {
           steps {
               echo "Hello World!"
               //input("Continue?")
               echo "OK"
               //input(
               //    message: 'Was this successful?', parameters: [
               //   [$class: 'BooleanParameterDefinition', defaultValue: true, description: '',
name: 'Please confirm you agree with this']
               //])

       /*
               script {
                   res = input(
                       message: 'Was this successful?', parameters: [
                       [$class: 'BooleanParameterDefinition', defaultValue: false, description:
'', name: 'Apple'],
                       [$class: 'BooleanParameterDefinition', defaultValue: false, description:
'', name: 'Banana']
                   ])
                                      print(res)
               }
*/
               script {
                   values = ['Apple', 'Banana', 'Peach']
                   parameters = []
                   values.each {
                       echo it
                       parameters.add( [$class: 'BooleanParameterDefinition', defaultValue:
false, description: '', name: it ] )
                   }

                   res = input(
                       message: 'Was this successful?', parameters: parameters
                   )
                                                         print(res)
               }


               //                input(
//                    message: 'What now?', parameters: [
//                        [$class: 'AppDetectorParamaterDefinition')
//                ])
                                  //echo result
                              // python scripts/aws_instances.py --what selftest --command start
           }
       }
   }
}

git Backup

gist