Unable to pass namespace parameter to kubernetes-cli plugin for Jenkins

2/17/2019

I have couple of different contexts with namespaces defined within my k8s cluster. Using different pipelines for Jenkins I'd like to switch between them. Idea is: based on git branch to do a deployment to specific environment. In order to do that I'd have to switch to existing production/dev/feature contexts and namespaces.

I want to use https://wiki.jenkins.io/display/JENKINS/Kubernetes+Cli+Plugin This is an example syntax for Jenkins scripted piepline:

Example:

node {
  stage('List pods') {
    withKubeConfig([credentialsId: '<credential-id>',
                    caCertificate: '<ca-certificate>',
                    serverUrl: '<api-server-address>',
                    contextName: '<context-name>',
                    clusterName: '<cluster-name>'
                    ]) {
      sh 'kubectl get pods'
    }
  }
}

And as you can see it does not accept anything for namespace

This is an example production context with namespace, which I'm using:

$ kubectl config get-contexts 
CURRENT   NAME             CLUSTER                           AUTHINFO                          NAMESPACE
*         aws-production   cluster.example.com   cluster.example.com       aws-production

And this is a result of running that step: enter image description here

How to resolve that issue? Is it possible to use namespaces using mentioned plugin at all? If not is there an alternative way to achieve context+namespace switch during Jenkins pipeline step?

EDIT: Seems that adding entry to .kube/config on Jenkins machine doesn't help for that issue. This plugin kubernetes-cli for Jenkins creates isolated context and does not care much about .kube/config :(

Manually forcing a config, doesn't help in this case too;

kubectl config use-context aws-production --namespace=aws-production --kubeconfig=/home/jenkins/.kube/config

-- Karol Flis
jenkins
jenkins-pipeline
jenkins-plugins
kubernetes

2 Answers

2/17/2019

The plugin doesn't have a namespace parameter but the ~/.kube/config does. So you could create 2 contexts to handle the two different namespaces. In your ~/.kube/config`

contexts:
- context:
    cluster: k8s.mycluster
    namespace: mynamespace1
    user: k8s.user
  name: clusternamespace1
- context:
    cluster: k8s.mycluster
    namespace: mynamespace2
    user: k8s.user
  name: clusternamespace2
-- Rico
Source: StackOverflow

2/18/2019

Thanks to help from official Jenkins IRC channel, solution below.

Solution: You have to pass raw .kube/config file as a credentialsId.

  1. Create new creadentials in Jenkins. I have used Secret file option.
  2. Upload you desired .kube/config and give it a name/id in credentials creation form.
  3. Pass the id name you have given to this credential resource to credentialsId field

withKubeConfig([credentialsId: 'file-aws-config', [..]]) ...

-- Karol Flis
Source: StackOverflow