Jenkins pipeline: kubectl: not found

Viewed 5835

I have the following Jenkinsfile:

node {
  stage('Apply Kubernetes files') {
    withKubeConfig([credentialsId: 'jenkins-deployer', serverUrl: 'https://192.168.64.2:8443']) {
      sh 'kubectl apply -f '
    }
  }
}

While running it, I got "kubectl: not found". I installed Kubernetes-cli plugin to Jenkins, generated secret key via kubectl create sa jenkins-deployer. What's wrong here?

2 Answers

I know this is a fairly old question, but I decided to describe an easy workaround that might be helpful.
To use the Kubernetes CLI plugin we need to have an executor with kubectl installed.

One possible way to get kubectl is to install it in the Jenkins pipeline like in the snipped below:
NOTE: I'm using ./kubectl get pods to list all Pods in the default Namespace. Additionally, you may need to change kubectl version (v1.20.5).

node {
  stage('List pods') {
    withKubeConfig([credentialsId: 'kubernetes-config']) {
        sh 'curl -LO "https://storage.googleapis.com/kubernetes-release/release/v1.20.5/bin/linux/amd64/kubectl"'  
        sh 'chmod u+x ./kubectl'  
        sh './kubectl get pods'
    }
  }
}

As a result, in the Console Output, we can see that it works as expected:

curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.20.5/bin/linux/amd64/kubectl
  ...
[Pipeline] sh
+ chmod u+x ./kubectl
[Pipeline] sh
+ ./kubectl get pods
NAME            READY   STATUS    RESTARTS   AGE
default-zhxwb   1/1     Running   0          34s
my-jenkins-0    2/2     Running   0          134m

You call kubectl from the shellscript step. To be able to do that the agent (node) executing the build needs to have kubectl available as executable.

Related