Configuring a Jenkins pipeline

2 minute read

CloudBees Previews relies on a CI system to build a previewable image. The CI pipeline must push an image tagged with the Git commit SHA of the pull request HEAD. The image name and tag must be the same in both systems to create preview environments.

Configuring a preview pipeline

In a .preview.yaml file, you can use the placeholder ${{env.commit.sha}} as an image tag. This might look as follows:

Example .preview.yaml file.
apiVersion: 1.0.0 previews: - name: myapp container: image: my.docker.registry/myapp:${{env.commit.sha}} (1) port: 8080
1 Use the commit SHA as image tag.

When CloudBees Previews deploys a preview, it substitutes the ${{env.commit.sha}} placeholder with the pull request’s HEAD Git commit SHA.

In a Jenkins pipeline, the Git commit SHA is exposed as environment variable GIT_COMMIT. The following Jenkinsfile snippet shows how it might look when building and pushing an image using kaniko:

Example Jenkinsfile building a previewable image.
pipeline {
  agent {
    kubernetes {
      yamlFile 'kaniko-build-pod.yaml'
    }
  }
  stages {
    stage('Build/push preview image') {
      environment {
        PREVIEW_APP_IMAGE = "my.docker.registry/myapp:${GIT_COMMIT}" (1)
      }
      steps {
        container('kaniko-builder') {
          sh '/kaniko/executor --destination $PREVIEW_APP_IMAGE --dockerfile `pwd`/Dockerfile --context `pwd`' (2)
        }
      }
    }
  }
}
1 Use the commit SHA as image tag, aligned with .preview.yaml.
2 Build and push the image using kaniko.

In case you are not using the Git plugin for the SCM checkout the GIT_COMMIT environment variable might not be set. Please consult your SCM plugin’s documentation for a variable that exposes the commit SHA or derive the SHA using the command git rev-parse HEAD.

Pull request head and merge build considerations

When Jenkins is configured to run pull request merge builds, the GIT_COMMIT environment variable value within the Jenkins job can differ from the ${{env.commit.sha}} value within the .preview.yaml. When the pull request is not based on the target branch’s HEAD, Jenkins merges the pull request locally as part of the build setup before running the build. GIT_COMMIT is in this case set to the SHA of the merge commit not the SHA of the pull request HEAD.

To prevent this from happening, you must either manually rebase your pull request before requesting a preview, or you can configure the Jenkins pipeline to run pull request head builds, rather than merge builds.

Configuring the GitHub Branch Source Plugin

When you use the GitHub Branch Source Plugin, your Jenkins pipeline runs pull request merge builds by default. You can configure pull request head builds by selecting The current pull request revision as discovery strategy in the Branch Sources tab of the Jenkins pipeline configuration view as shown below:

jenkins github branch source plugin pr head builds