How to define multiple containers in declarative pipeline?
This isnt a solution to your problem, but is some information I found after looking.
The KubernetesDeclarativeAgent only has a single containerTemplate
. Whichever containerTemplate
is at the bottom of your collection of containers will be the one that is used.
In your example it will be containtertwo
.
You cant have multiple top level agents
, and you cant have multiple kubernetes
within an agent. And now you cant have multiple containers. I would prefer if an error or warning of some kind was thrown for this.
There are 2 work arounds I can think of. If you must use declarative, then you can add an agent
to your stage
, but this can lead to its own issues. The other is the scripted pipeline, which is what I am going to do.
The documentation on this leaves much to be desired.
You can achive that with the help of a pod template file. I use the following one to deploy my app on kubernetes:
apiVersion: v1kind: Podmetadata: labels: label: dockerspec: containers: - name: docker image: jenkins/jnlp-agent-docker command: - cat tty: true volumeMounts: - mountPath: '/var/run/docker.sock' name: docker-socket - name: kubectl image: bitnami/kubectl command: - cat tty: true volumes: - name: docker-socket hostPath: path: '/var/run/docker.sock' securityContext: runAsUser: 0
Then use this in a declarative pipeline:
stage('Deploy') { when { anyOf { branch 'master'; tag '' } } agent { kubernetes { defaultContainer 'kubectl' // All `steps` instructions will be executed by this container yamlFile 'path/to/pod/template.yaml' } } steps { container('docker') { sh 'echo This is executed in the docker container' } }}
You can also specify the template in the Jenkinsfile with the help of yaml
option instead of yamlFile
, you just need to use a multiline string there.