How to deploy on Kubernetes using kubectl sh in Jenkinsfile

3/17/2019

I'm trying to create a pipeline that is triggered after a commit in git. I have installed minikube using kvm2 driver. However I am not sure if everything is setup as it should. Jenkins has been installed previously and it doesn't run on kubernetes.

Below is my Jenkinsfile.

pipeline {

    environment {
        ....
    }

    agent any

    stages {

        stage ('Clone') {
            ....
        }

        stage('Build') {
            ....
        }

        stage(‘Containerize’) {
            .... build images with docker
        }

        stage('Deploy Image') {
            .... push images on Docker hub
        }

        stage('Deploy Application') {
            steps {
                // Create namespace if it doesn't exist
                sh("kubectl get ns development || kubectl create ns development")
               .... 
            }
        }
    }
}

I also configured Kubernetes as Cloud. I've added kubernetes URL as the one show in ./kube/config kubernetes server certificate as the content of /.minikube/ca.crt credentials created with the

sudo openssl pkcs12 -export -out kubernetes.pfx -inkey apiserver.key -in apiserver.crt -certfile ca.crt -passout pass:jenkins

The problem I have is this:

[Pipeline] { (Deploy Application)
[Pipeline] sh
+ kubectl get ns development
The connection to the server localhost:8080 was refused - did you specify the right host or port?

Is this something related to RBAC? I tried to use the Secret Token using kubectl create serviceaccount jenkins and copy the token but when I tested the connection it didn't work.

I'm not sure if this is the right way to deploy on Kubernetes using a pipeline. Please suggest if there's a better way to deploy my microservices.

-- Gfalco
jenkins-pipeline
kubectl
kubernetes
minikube

1 Answer

3/17/2019
  • There are alot of many ways to deploy to kubernetes , use the one that works for you better

  • the above error is related to the address/API endpoint of the cluster , so it could not found your cluster , you need to provide the kubeconfig in some suitable location or use some other way of connecting to cluster

Something like:

kubectl --kubeconfig=/path/to/kubeconfig-file get ns development || kubectl --kubeconfig=/path/to/kubeconfig-file  create ns development")

As always , please try and run those commands manually and make sure they work before putting them in automation/pipeline

-- Ijaz Ahmad Khan
Source: StackOverflow