fabric8io / fabric8-pipeline-library

Fabric8 Pipeline for Jenkins
Apache License 2.0
438 stars 211 forks source link
fabric8-pipeline jenkins kubernetes openshift pipelines-as-code

Table of Contents

Fabric8 Pipeline Library

This git repository contains a library of reusable Jenkins Pipeline steps and functions that can be used in your Jenkinsfile to help improve your Continuous Delivery pipeline.

fabric8 logo

The idea is to try promote sharing of scripts across projects where it makes sense.

How to use this library

This library is intended to be used with fabric8's Jenkins image that is deployed as part of the fabric8 platform.

To use the functions in this library just add the following to the top of your Jenkinsfile:

@Library('github.com/fabric8io/fabric8-pipeline-library@master') _

That will use the master branch of this library. You can if you wish pick a specific tag or commit SHA of this repository too.

Making changes

Feel free to reuse a version of this library as is. However if you want to make changes, please fork this repository and change it in your own fork!

Then just refer to your fork in the @Library() annotation as shown above.

If you do make local changes we'd love a Pull Request back though! We love contributions and pull requests!

Requirements

These flows make use of the Fabric8 DevOps Pipeline Steps and kubernetes-plugin which help when working with Fabric8 DevOps in particular for clean integration with the Hubot chat bot and human approval of staging, promotion and releasing.

Functions from the Jenkins global library

Approve

example..

    approve {
      version = '0.0.1'
      console = 'http://fabric8.kubernetes.fabric8.io'
      environment = 'staging'
    }

Deploy Project

in the case of an aborted approval

WARNING this function is deprecated. Please change to use getDeploymentResources{}

If CI fails and updates are required as a result of the dependency upgrade then

Automating this has saved us a lot of time during the release pipeline

    def properties = []
    properties << ['<fabric8.version>','io/fabric8/kubernetes-api']
    properties << ['<docker.maven.plugin.version>','io/fabric8/docker-maven-plugin']

    updatePropertyVersion {
      updates = properties
      repository = source // if null defaults to http://central.maven.org/maven2/
      project = 'fabric8io/ipaas-quickstarts'
    }

Wait Until Artifact Synced With Maven Central

When working with open source java projects we need to stage artifacts with OSS Sonatype in order to promote them into maven central. This can take 10-30 mins depending on the size of the artifacts being synced.

A useful thing is to be notified in chat when artifacts are available in maven central as blocking the pipeine until we're sure the promote has worked.

If CI fails and updates are required as a result of the dependency upgrade then

    waitUntilPullRequestMerged {
      name = 'fabric8io/fabric8'
      prId = '1234'
    }

fabric8 release

These functions are focused specifically on the fabric8 release itself however could be used as examples or extended in users own setup.

The core fabric8 release consists of multiple Java projects that generate Java artifacts, docker images and kubernetes resources. These projects are built and staged together, automatically deployed into a test environment and after approval promoted together ready for the community to use.

When a project is staged an array is returned and passed around functions further down the pipeline. The structure of this stagedProject array is in the form [config.project, releaseVersion, repoId]

    def stagedProject = stageProject {
      project = 'fabric8io/ipaas-quickstarts'
      useGitTagForNextVersion = true
    }

One other important note is on the fabric8 project we don't use the maven release plugin or update to next SNAPSHOT versions as it causes unwanted noise and commits to our many github repos. Instead we use a fixed development x.x-SNAPSHOT version so we can easily work in development on multiple projects that have maven dependencies with each other.

Now that we don't store the next release version in the poms we need to figure it out during the release. Rather than store the version number in the repo which involves a commit and not too CD friendly (i.e. would trigger another release just for the version update) we use the git tag. From this we can get the previous release version, increment it and push it back without triggering another release. This seems a bit strange but it has been holding up and has significantly reduced unwanted SCM commits related to maven releases.

Promote Artifacts

    gitTag {
      releaseVersion = '0.0.1'
    }

Deploy Remote OpenShift

Deploys the staged fabric8 release to a remote OpenShift cluster

NOTE in order for images to be found by the remote OpenShift instance it must be able to pull images from the staging docker registry. Noting private networks and insecure-registry flags.

    node {
      deployRemoteOpenShift {
        url = openshiftUrl
        domain = 'staging'
        stagingDockerRegistry = openshiftStagingDockerRegistryUrl
      }
    }

Deploy Remote Kubernetes

Deploys the staged fabric8 release to a remote Kubernetes cluster

NOTE in order for images to be found by the remote OpenShift instance it must be able to pull images from the staging docker registry. Noting private networks and insecure-registry flags.

    node {
      deployRemoteKubernetes {
        url = kubernetesUrl
        defaultNamespace = 'default'
        stagingDockerRegistry = kubernetesStagingDockerRegistryUrl
      }
    }

Add Annotation To Build

Add an annotation to the matching openshift build

    @Library('github.com/fabric8io/fabric8-pipeline-library@master')
    def dummy
    node {
        def utils = new io.fabric8.Utils()
        utils.addAnnotationToBuild('fabric8.io/foo', 'bar')
    }

Understanding how it works

Most of the functions provided by this library are meant to run inside a Kubernetes or Openshift pod. Those pods are managed by the kubernetes plugin. This library abstracts the pipeline capabilities of kubernetes plugin so that it makes it easier to use. So for example when you need to use a pod with maven capabilities instead of defining something like:

podTemplate(label: 'maven-node', containers: [
    containerTemplate(name: 'maven', image: 'maven:3.3.9-jdk-8-alpine', ttyEnabled: true, command: 'cat')
  ],
  volumes: [secretVolume(secretName: 'shared-secrets', mountPath: '/etc/shared-secrets')]) {

    node('maven-node') {
        container(name: 'maven') {
            ...
        }
    }
  }

You can just use the mavenTemplate provided by this library:

mavenTemplate(label: 'mylabel') {
    node('mylabel') {
        container(name: 'maven') {
          ...
        }
    }
}

or for ease of use you can directly reference the mavenNode:

mavenNode {
    container(name: 'maven') {
        ...
    }
}

Template vs Node

A template defines how the jenkins slave pod will look like, but the pod is not created until a node is requested. When a node is requested the matching template will be selected and pod from the template will be created.

The library provides shortcut function both to nodes and templates. In most cases you will just need to use the node. The only exception is when you need to mix and match (see mixing and matching).

The provided node / template pairs are the following:

Maven Node

Provides maven capabilities by adding a container with the maven image. The container mounts the following volumes:

The maven node and template support limited customization through the following properties:

Example:

mavenNode(mavenImage: 'maven:3.3.9-jdk-7') {
    container(name: 'maven') {
        sh 'mvn clean install'
    }
}

Docker Node

Provides docker capabilities by adding a container with the docker binary. The container mounts the following volumes:

Host path mounts are not allowed everywhere, so use with caution. Also note that the mount will be mounted to all containers in the pod. This means that if we add a maven container to the pod, it will have docker capabilities.

The docker node and template support limited customization through the following properties:

Example:

mavenNode(dockerImage: 'docker:1.11.2') {
    container(name: 'docker') {
        sh 'docker build -t myorg/myimage .'
    }
}

Clients Node

Provides access to the kubectl and oc binaries by adding a container to the pod that provides them. The container is configured exactly as the docker container provided by the dockerTemplate.

Example:

clientsNode(clientsImage: 'fabric8/builder-clients:latest') {
    container(name: 'clients') {
        sh 'kubectl create -f ./target/classes/META-INF/kubernetes/kubernetes.yml'
    }
}

Release Node

Provides docker capabilities by enriching the jenkins slave pod with the proper environment variables and volumes.

Also the following environment variables will be available to all containers:

These variables will obtain their values from jenkins container (they will be copied).

Example:

releaseTemplate {
    mavenNode {
    container(name: 'docker') {
        sh 'docker build -t myorg/myimage .'
    }
}

Mixing and matching

There are cases where we might need a more complex setup that may require more than a single template. (e.g. a maven container that can run docker builds).

For this case you can combine add the docker template and the maven template together:

dockerTemplate {
    mavenTemplate(label: 'maven-and-docker') {
        node('maven-and-docker') {
             container(name: 'maven') {
                sh 'mvn clean package fabric8:build fabric8:push'
             }
        }
    }
}

The above is equivalent to:

dockerTemplate {
    mavenNode(label: 'maven-and-docker') {
        container(name: 'maven') {
            sh 'mvn clean package fabric8:build fabric8:push'
        }
    }
}

In the example above we can add release capabilities too, by adding the releaseTemplate:

        dockerTemplate {
            releaseTemplate {
                mavenNode(label: 'maven-and-docker') {
                    container(name: 'maven') {
                        sh """
                            mvn release:clean release:prepare
                            mvn clean release:perform
                        """
                    }
                }
            }
        }

Creating and using your own templates

If the existing selection of templates is limiting you can also create your own templates. Templates can be created either by using the Jenkins administration console or by using the groovy.

Using the Jenkins Administration Console

In the console choose Manage Jenkins -> Configure System and scroll down until you find the section Cloud -> Kubernetes. There you can click to Add Pod Template to create your own using the wizard.

Then you can just instantiate the template by creating a node that references the label to the template:

        node('my-custom-template') {
        }

Note: You can use this template to mix and match too. For example you can combine your custom template with an existing one:

        mavenNode(inheritFrom: 'my-custom-template') {
        }