How to Deploy to Kubernetes from a Jenkins Pipeline
Bind a kubeconfig credential with withKubeConfig, run kubectl set image, then wait for the rollout to finish.
Use the Kubernetes CLI plugin's withKubeConfig (or a Secret file credential) to point kubectl at your cluster, update the image, and gate the build on rollout status.
Roll out inside withKubeConfig
The credential supplies cluster access; rollout status makes the stage fail on a stuck rollout.
Jenkinsfile
pipeline {
agent any
stages {
stage('Deploy') {
when { branch 'main' }
steps {
withKubeConfig([credentialsId: 'prod-kubeconfig']) {
sh 'kubectl set image deployment/app app=myorg/app:${BUILD_NUMBER}'
sh 'kubectl rollout status deployment/app --timeout=120s'
}
}
}
}
}Gotchas
withKubeConfigcomes from the Kubernetes CLI plugin; without it, fall back to afilecredential bound viawithCredentials.- Always
kubectl rollout status --timeoutso a stalled rollout aborts the stage instead of passing. - The agent must have
kubectlinstalled (or run the stage in a container image that has it).
Related guides
How to Deploy to Kubernetes from GitHub ActionsDeploy to Kubernetes from GitHub Actions - configure kubectl with a secret kubeconfig (or cloud OIDC), set th…
How to Deploy on a Tag in a Jenkins PipelineDeploy on a tag in a Jenkins multibranch pipeline with the buildingTag and tag when conditions so only tag bu…