Issue
I would like to trigger a downstream Pipeline build, and I would like to pass a parameter to that build to specify which Docker image to use in the Kubernetes Pod Template for the agent. One use case for this would be when I build and push a new tag of a Docker image in an upstream build, and I want to use that new image in a downstream Pipeline.
Resolution
In your upstream Pipeline, trigger the downstream Pipeline using the build step:
build job: 'downstream', parameters: [string(name: 'IMAGE', value: 'ubuntu:18.04')]
In the Jenkinsfile of your 'downstream' Pipeline job, use code similar to:
pipeline {
parameters {
string defaultValue: 'ubuntu:latest', description: 'Docker image and tag to use', name: 'IMAGE', trim: true
}
agent {
kubernetes {
yaml """
apiVersion: v1
kind: Pod
spec:
containers:
- name: shell
image: $IMAGE
command:
- sleep
args:
- infinity
"""
defaultContainer 'shell'
}
}
stages {
stage('Main') {
steps {
sh 'cat /etc/os-release'
}
}
}
}
The important points in this code are:
-
the
IMAGEstring parameter has a reasonable default value to allow the build to work normally -
The
yaml """uses a Triple-double-quoted string so that the$IMAGEvariable is evaluated within that block -
the
defaultContainer 'shell'is used instead of thecontainer('shell')syntax inside of the stage (either choice is valid): https://github.com/jenkinsci/kubernetes-plugin#pipeline-support
If the 'downstream' build is run with the default parameters, you would see:
...
Pipeline] {
[Pipeline] container
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Main)
[Pipeline] sh
+ cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.1 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.1 LTS"
VERSION_ID="20.04"
...
If the 'downstream' build is triggered with build job: 'downstream', parameters: [string(name: 'IMAGE', value: 'ubuntu:18.04')] you would see this in the console output of the build:
...
[Pipeline] {
[Pipeline] container
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Main)
[Pipeline] sh
+ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.5 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.5 LTS"
VERSION_ID="18.04"
...