Step 9 - Kubernetes
In this step, we replace the simple docker run deployment with a Kubernetes deployment using kubectl.
Jenkinsfile¶
Here is the Jenkinsfile for this step. Source code: 30-09-Jenkinsfile-sonarqube-docker-build-push-anchore-deploy-to-kubernetes.
pipeline {
agent any
options {
disableConcurrentBuilds()
disableResume()
buildDiscarder(logRotator(numToKeepStr: '10'))
timeout(time: 1, unit: 'HOURS')
}
tools {
maven 'maven-3.6.3'
}
environment {
DATE = new Date().format('yy.M')
TAG = "${DATE}.${BUILD_NUMBER}"
scannerHome = tool 'sonarscanner'
}
stages {
stage ('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Docker Build') {
steps {
script {
docker.build("vigneshsweekaran/hello-world:${TAG}")
}
}
}
stage('Pushing Docker Image to Dockerhub') {
steps {
script {
docker.withRegistry('https://registry.hub.docker.com', 'docker_credential') {
docker.image("vigneshsweekaran/hello-world:${TAG}").push()
docker.image("vigneshsweekaran/hello-world:${TAG}").push("latest")
}
}
}
}
stage('Deploy to Kubernetes'){
steps {
withCredentials([sshUserPrivateKey(credentialsId: 'vm-key', keyFileVariable: 'SSH_PRIVATE_KEY_PATH')]) {
sh "scp -i $SSH_PRIVATE_KEY_PATH -o StrictHostKeyChecking=no deployment/deployment.yaml opc@k8s.letspractice.tk:/tmp/."
sh "ssh -i $SSH_PRIVATE_KEY_PATH -o StrictHostKeyChecking=no opc@k8s.letspractice.tk 'kubectl apply -f /tmp/deployment.yaml'"
}
}
}
}
post {
always {
deleteDir()
}
}
}
Detailed Explanation¶
Deploy to Kubernetes Stage¶
sshUserPrivateKey: Extracts the private key from Jenkins credentials and saves it to a temporary file (SSH_PRIVATE_KEY_PATH).scp: Securely copies thedeployment.yamlfrom our workspace to the/tmpdirectory on the remote Kubernetes master/jump host.ssh ... 'kubectl apply ...': Connects to the remote host and executes thekubectlcommand to apply the configuration.
Important Tips¶
Note
This pattern (SSHing to a jump host) is common, but advanced setups often use the Kubernetes plugin to deploy directly from the Jenkins slave (if it's inside the cluster) or use a GitOps operator like ArgoCD.
Quick Quiz¶
Quick Quiz¶
Which command is used to apply a configuration file to a Kubernetes cluster?
What is the purpose of the sshUserPrivateKey credential type in Jenkins?
Why might you copy a file to /tmp on the remote server before applying it?
📬 DevopsPilot Weekly — Learn DevOps, Cloud & Gen AI the simple way.
👉 Subscribe here