Search code examples
ubuntujenkinsamazon-ec2kubectl

Not Able to execute kubectl command in jenkins pipeline


Not able to run Kubectl command in jenkins pipeline, But works fine through command line.

I am running a pipeline on ec2 ubuntu instance where I have installed jenkins and at the end it deploys the app to an eks cluster (ec2 is connected to cluster). Everything is happening from my main jenkins installation, I am not using any jenkins agents.

Ihave installed kubectl command on the ec2 instance using which I successfully connected to the eks cluster using normal cmd line. I am able to run the kubectl command from anywhere in the system. But when I run the kubectl apply -f . command in pipeline it says

kubectl apply -f deployment.yaml
/var/lib/jenkins/workspace/java-app-ECR@tmp/durable-b43cd65c/script.sh: 4: kubectl: not found

Also my jenkins is executing the commands with the same user that I am using to execute the cmd line commands. When i give full path of the kubectl command in pipeline it says permission denied

/home/ubuntu/bin/kubectl apply -f deployment.yaml
/var/lib/jenkins/workspace/java-app-ECR@tmp/durable-47c860e3/script.sh: 4: /home/ubuntu/bin/kubectl: Permission denied

but my user 'ubuntu' owns the files located in this path

ubuntu:~/bin$ pwd
/home/ubuntu/bin
ubuntu:~/bin$ ll
total 43996
drwxrwxr-x  2 ubuntu ubuntu     4096 Jun 20 13:06 ./
drwxr-x--- 12 ubuntu ubuntu     4096 Jun 20 13:06 ../
-rwxrwxr-x  1    777 ubuntu 45039616 Jun 20 13:06 kubectl*

Tried this one How to setup kubectl within jenkins didnt help much Please guide


Solution

  • If you installed kubectl recently, consider restarting Jenkins or the ec2 instance and see if that makes Jenkins pick up the command. If not, add the kubectl bin to the path within Jenkins itself (see this answer).

    As for the second part, Jenkins usually creates its own user called jenkins, and most likely doesn't use your ubuntu user. Try checking your users list to see if a Jenkins user has been created. If it has, give file permissions to the jenkins user and try again.