Skip to content
Switch branches/tags
Go to file
Cannot retrieve contributors at this time
798 lines (509 sloc) 23.6 KB
path title
Learnings: Jenkins

Installing Jenkins on RHEL box

First, install Java 8... (see Cloud9InstallingJava8)

  1. Execute commands on:
  2. $ sudo service jenkins start
  3. In /etc/sysconfig/jenkins set JENKINS_LISTEN_ADDRESS to (see:
  4. ???????

On Ubuntu box




See also:


Jenkins server Operations <<Learning_Jenkins_Ops>>

Configuration <<Learning_Jenkins_Ops_Configuration>>

Jenkins Docker provides and give a text file so have a Jenkins configured via code (not manual clicking).

Other configuration done in Groovy. (including plugin configuration!)


Groovy init script happens every server boot.

Can be separated out into separate scripts, can be tested using built in Groovy console.

Manage Jenkins -> Scripting Console to try these (changes will be in memory only).

Job configuration <<Learning_Jenkins_Ops_Job_Configuration_File_Storage_Location>>

Source for much of this: Extending Jenkins

lives in $JENKINS_HOME each job with it's own folder and config.xml with the configurations for that job. (some other misc files too)

... and secrets

can use Consul/Vault for service discovery, secret storage

THEN use that in your Groovy init scripts (see Learning_Jenkins_Ops_Scripting_Configuration ) to ie do a curl and ask Vault for things and set it to env variable or write to a file, whatever.

And Groovy Scripting <<Learning_Jenkins_Scripting>>

Can do a bunch of things via groovy scripting interface (and either putting them as init scripts or using the scripting console).


  • Creating a bunch of jobs/projects
  • maintenance tasks

See also

Jenkins Creating Plugins <<Learning_Jenkins_Plugin_Creation>>

If have set up Maven settings.xml with Jenkins plugin repo, can do:

$ mvn -U

For archetype for Maven plugin.

mvn package creates a .hpi file: what you provide to Jenkins.

Bunch of helper stuff mvn hpi:run to ie boot a local dev copy of Jenkins so you can try out your plugin.

but what about extending existing plugins?

Extension Points: documented / auto created by Extension Indexer.

Getting started

Note: @DataBoundConstructor: annotating class with this means it'll be called when user selects this task/build type.

Jenkins Concepts

Master Node

has access to all data, config, options etc. Not recommended you run jobs here

(Build) Agents (Nodes)

Only a lightweight Jenkins agent installed here


On master: Manage Jenkins -> Manage Nodes -> New Node form.


How many concurrent jobs can be run on that (agent)


Jenkins Build tools are nifty ways admins can install tools your projects may require in order to be built.

Some plugins add additional tool types. Tools can be dynamically

Manage Jenkins -> Global Tool Configuration.

Tools can be installed on demand, or can point to existing install of software.

Jenkinsfiles can then declare they use those tools using $TOOLNAME 'VERSION_IN_STRING. Example: tool 'node8.11' (where I had previously installed a Node tool using the Node plugin and named it "node8.11").


tool name: 'node8.11', type: 'SOMETHING_GOES_HERE'

Not completely sure what type is here. Q: maybe the "type" of the tool in $JENKINS_HOME/tools ?? ( ie is this the class in the plugin that extend ??)


Each agent can specify their own locations for various Tools. Thus with a single name you can refer to ("wherever this tool may be on our agents")

Q: What tools and tool locations are on all my Nodes?

A: Maybe this Jenkins console shell script will help?

See also:

  • Learning_Jenkins_Declarative_DSL_Using_Tools

Job Types <<Learning_Jenkins_Job_Types>>


Gives build section where you enter a command to run


Gives you blanks for a Root POM file and the goals to send to Maven

JENKINS can send artifact to Nexus


can put build steps in job, or in file Jenkinsfile.

plugins called here need to support Pipelines


Configuration page:

  • Pipeline section: has two options: pipeline script; pipeline script from SCM. (LATTER one is what lets Jenkinsfiles be stored with the code repository....

Q: These details here is what Jenkins uses to do the auto check out of your project? A: YES! These are using in checkout scm step.

And Security <<Learning_Jenkins_Pipelines_Security>>

Pipeline Libraries <<Learning_Jenkins_Pipelines_Libraries>>

Less sandbox requirements

Multi configuration

When you need to run a series of tests ie in multiple OSes (or browsers)


Can specify items shared by all jobs in the folder:

  • libraries (untrusted)
  • Pipeline model definitions
  • top level label to search for agents under
  • ACLs for all items in folder

Multibranch pipeline project

creates new pipeline branches for new branches it sees in a (single) SCM repo

Can set specific properties for certain branch names

Github Organization

Multibranch pipeline projects for arbitrary repos in a Github organization.


Two modes: Declarative and Scripted pipelines. (Scripted has more procedural code / DSL; )


Ways of triggering this:

  • SSHing to Jenkins application itself then running 'declarative-linter'
  • Using Jenkins REST API
  • adding pipeline step that calls validateDeclarativePipeline (but umm inception problems????)

Scripted Model


node("finder_label") {
  stage('Source') {
    git 'git://'

  stage('Build') {
    sh "make build"

Declarative Model

(Blue Ocean UI's editor and display meant to work with this better)


pipeline {
  agent { label: "finder_label" }
  stages {
    stage("Source") {
      steps {
        git 'git://'

    stage("Build") {
      steps {
        sh "make build"

See also:

  • Learning_Jenkins_Declarative_DSL_Embedding_Groovy
  • Learning_Jenkins_Declarative_DSL_Using_Tools
  • Learning_Jenkins_Declarative_DSL_Getting_Variables_Out
  • Learning_Jenkins_Declarative_DSL_Useful_API

Declarative mode code editing tools

Has built in Snippet creator, MPW Commando style. In normal mode left sidebar should be a Pipeline Syntax link - this will let you select the pipeline step you want and will output copy-pasteable text with your parameters.


Can also break these out into libraries

pipeline {
  agent {}
  stages {
    stage("Build") {
      steps {



  • stash / unstash <-- save some files and retrive them on the next stage which maybe you've set up to run on some other machine


In script stage

pipeline {
  agent any
  stages {
    stage("Build") {
      steps {
        script {
          def currentDate = new Date() // only available in this script block!

Free floating functions

pipeline {
  agent any
  stages("Build") {
    steps {

def goJanetGo() {
  echo "Janet, bring me a cactus"

( Supported in post mid 2017 versions of Jenkins???, may be some restrictions ).


Section of the declarative Jenkinsfile: tools.

pipeline {
  agent any
  tools {
    maven 'maven-version-here'

This will be AUTO ADDED to any sh command's $PATH variable, so you don't have to prefix PATH with it.

Specifying hard to know tools

  1. Use the Snippet Generator: tools. This will let you pick what tool type (ie custom tool, git tool) and what tool name
  2. or just do: tool( name: 'gitgit', type: 'git' )


... but maybe you're paranoid

pipeline {
  agent any
  tools {
    maven 'maven-version-here'

  environment {
    MY_MAVEN_HOME = tool 'maven-version-here'

  steps {
    sh "$MY_MAVEN_HOME"

See also:


(in a script step...)

env.MY_VALUE = 1+2




pipeline {
  agent {}
  stages {
    stage("Deploy Build") {
      when {
        expression { params.BRANCH_NAME == "master" }

      steps {
        echo "I only deploy on changes to master!"

    stage("Release") {
      when {
        allOf {
          expression { params.BRANCH_NAME == "master"}
          expression { params.BUILD_TYPE == "release" }

about sh

Jenkins auto adds set -e to shell scripts.


will return true if is unix, can be used in if statement or expression??)


fileExists "build-overrides/thing"


Can make REST calls (and authorized ones too)!

def response = httpRequest contentType: 'APPLICATION_JSON', url: ''
def responseJSON = readJSON text: response.content
echo responseJSON.someAttribute

Authorized ones are similar, but use the credentials. Pass the key to your credentials

def response = httpRequest url: '', authentication: 'MY_CRED_ID'

Libraries and external code



def myFn(what) {
  echo "HI!"

return this

Jenkinsfile pipeline() { stages() { stage("Build") { script { def module = load "build-scripts/test.groovy" // cwd is checked out project root module.myFn 'hi' }



Workflow Remote Loader plugin allows you to pull random code from SCM - then run it just like the load function


Source structure:

    globalVarsAndFunctionsThisLibraryIntroduces.txt <-- adds snippet generator docs

src: added to classpath resources: use with libraryResource step vars: global vars or scripts accessible from pipeline scripts

NOTE WHEN USING DECLARATIVE PIPELINE: src/ directory does not work (May, 2017). So use vars area.

Pulled down from SCM repo. Legacy mode: git server served by Jenkins the server.

Can configure these at the global shared librares, or at the folder level.


There's two ways to test your jenkins shared library work. At least this works for items in the vars folder...

Use the replay button in a build

When you do a build on a folder configured to pull shared libraries, you can hit the replay button for any build that at least passes syntax checks of the Groovy.

You will have one text box for every file the shared library has in it.

Commit your work to a branch in the shared library repo and have your target use that

This requires some tweaking of the built project's Jenkinsfile.



pipeline {

NOTE: that underscore after the annotation is required. (I have no idea what that's about).

Jenkins Plugins I've used


Node.js Jenkins Plugin


Manage Jenkins (popup version) -> Managed Files -> Add New Config

With Node.js plugin, new file type is: npmrc includes a template of a .npmrc file.

NOTE the ID (not name) of the configuration file (maybe change this to something human).

Using this in a pipeline

pipeline {
  agent any
  steps {
    nodejs(nodeJSInstallationName: 'MY_NODEJS_TOOL_NAME_HERE', configId: 'ID_OF_THE_CONFIG_FILE') {
      sh "npm install"

Node.js plugin will auto copy the managed file into the right place for npm and now settings from there (like loggingLevel or registry will be set appropriately).


Nexus Artifact Plugin.

Personal Opinion: artifact uploading should be separated from artifact building. If we only know how to use Maven (release plugin) to upload to Nexus, then what happens when we need to upload Node modules? Or Python? Do we force these languages through an (unnatural) Maven workflow? Do we figure out how to upload to Nexus using Yet Another Build Tool?

If we always do it through a Jenkins plugin then we can just point Jenkins at where our artifacts build and let it take care of the uploading.


pipeline {
  agent any
  stage("Upload Artifact") {
      nexusVersion: 'nexus3',
      protocol: 'http',
      nexusUrl: '',
      groupId: 'com.example',
      version: version,
      repository: 'RepositoryName',
      credentialsId: 'CredentialsId',
      artifacts: [
        [artifactId: projectName,
         classifier: '',
         file: 'my-service-' + version + '.jar',
         type: 'jar']

Works great for non Java projects!!!

For Java projects see Java_Maven_Saving_Releases_To_Nexus, there's non-obvious factors at play!






After installing Bitbucket plugin(s), Go into Configure system, -> Bitbucket Endpoints. Add -> Bitbucket Server, put your server name here.

THEN each Bitbucket related item will have a Server option, where you can pick real bitbucket or your Bitbucket.

NOTE: When you do a multi-branch group the "OWNER" in the Configure screen is the SHORT NAME of the project (read: the /projects/INIT/something <-- the INITials here>)

unable to fetch ref errors with pull requests

Bitbucket PRs live on their own separate branches, like Github PRs do.

This branch is updated lazily.

There are two ways to get it to update:

  1. Someone visits the pull request page
  2. Use the Bitbucket Source plugin 2.11.12 which adds a mergability check which has a side effect of updating the PR branch


Q: "What groups does this user belong to, so I can use the Role Strategy Plugin and the Manage And Assign Roles + Project Roles pattern to make sure they have access to the correct top level items?

A: Have them visit /whoAmI/ <-- this will list their roles ("Authorities") so you can make sure they match

  • [NOTE]: Q: Do roles only apply to views ??? (that was an experience once...)


Using the Cobertura Plugin.

In Pipeline syntax:

                step([$class: 'CoberturaPublisher', autoUpdateHealth: false, autoUpdateStability: false, coberturaReportFile: 'coverage/cobertura-coverage.xml', failUnhealthy: false, failUnstable: false, maxNumberOfBuilds: 0, onlyStable: false, sourceEncoding: 'ASCII', zoomCoverageChart: false])



Init script run on launch:

  • $JENKINS_HOME/init.groovy
  • $JENKINS_HOME/init.groovy.d/*.groovy <-- scripts in here run in alphabetical order

using libraries in init script


First, get a list of plugins you have currently installed (if you are duplicating an existing install...)

def plugins = []
Jenkins.instance.pluginManager.plugins.each { plugin ->
    if ( (plugin.isBundled() == false) && (plugin.isEnabled() == true ) ) {
      	plugins << "'${plugin.shortName}'"

Then with this list, run:

def installPlugins = ["github-issues"]

installPlugins.each { plugin ->
    def instance = Jenkins.getInstance()
    def pm = instance.getPluginManager()
    def uc = instance.getUpdateCenter()
    if (pm.getPlugin(plugin)) {
        println "Plugin ${plugin} already installed"
    } else {
        println "Looking UpdateCenter for " + plugin
        def pluginObject = uc.getPlugin( plugin )
        def installFuture = pluginObject.deploy()
        while(!installFuture.isDone()) {
            println "Waiting for plugin install: " + plugin



Unlike Plugins, broad based approach apparently won't work....

Iterating through Tools <<Learning_Jenkins_Provisioning_Init_Script_Tools_Listing_Tools>>

But can iterate through all tools on machine like so:


for (ToolDescriptor desc : ToolInstallation.all()) {
  for (ToolInstallation inst : desc.getInstallations()) {
    print("\tInstallation Class: ${}")
    println('\tTool Name: ' + inst.getName());
    //print("\tTool Location: " + inst.location);

Because the installation of a tool is dependent / can be specialized by the Node it's installed on, you must iterate every agent to know where the tool is installed.

Iterating through installations of Tools / Extensions



You use the values from this list and pass that into getExtensionList down below

Installing tool with a hard coded path (Maven example) <<Learning_Jenkins_Provisioning_Init_Script_Installing_Tools_Example>>

import jenkins.model.* 

def looking_for_maven_install_named = "apache-maven-3.5.3"
def maven_install_location          = "/usr/local/maven"

// ^^^^ Q: where did we get that class name? Jenkins.instance.getExtensionList( )

b=(a.installations as List); 
def found = false
b.each {
  found = found || ( == looking_for_maven_install_named)
if (found) {
  println "did have an installation of ${looking_for_maven_install_named}"
} else {
  b.add(new hudson.tasks.Maven.MavenInstallation(looking_for_maven_install_named, maven_install_location, [])); 

Installing tool with auto install (Ant example)

def instance = Jenkins.getInstance()

// Ant
println "--> Configuring Ant"
def desc_AntTool = instance.getDescriptor("hudson.tasks.Ant")

def antInstaller = new AntInstallation(ant_version)
def ant_installations = desc_AntTool.getInstallations()

def installSourceProperty = new InstallSourceProperty([antInstaller])
def ant_inst = new AntInstallation(
  "ADOP Ant", // Name
  "", // Home

ant_installations += ant_inst
desc_AntTool.setInstallations((AntInstallation[]) ant_installations)

// Save the state

See also:


CustomTools are a bit different than the tools / installers built into a plugin.

Adding a custom tool

import jenkins.model.* 
import com.cloudbees.jenkins.plugins.customtools.CustomTool;
import com.synopsys.arc.jenkinsci.plugins.customtools.versions.ToolVersionConfig;


def installs = a.getInstallations()
def found = installs.find { == "gcc"

if ( found ) {
	println "gcc is already installed"
} else {
 	println "installing gcc tool"
  	def newI = new CustomTool("gcc", "/usr/local/gcc/", null, "bin", null, ToolVersionConfig.DEFAULT, null)
	installs += newI
	a.setInstallations( (com.cloudbees.jenkins.plugins.customtools.CustomTool[])installs );

This will install a custom tool configured as such:

  • name: "gcc"
  • Exported Paths: "bin"
  • Installation Directory: "/usr/local/gcc"

Checking to see if a custom tool is installed follows the same pattern as any other plugin instance. (see Learning_Jenkins_Provisioning_Init_Script_Installing_Tools_Example).

Source code systems and common questions

How do I get the current git commit?

there used to be env.GIT_COMMIT but I found it missing the other day UPDATE: it's missing if you use skipDefaultCheckout. But still.

do something like this instead

def res = checkout scm


Book Recommendations