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:
.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 |
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:
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 |
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: