<p>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.</p>

<p>I want to use <a href="https://wiki.jenkins.io/display/JENKINS/Kubernetes+Cli+Plugin" rel="nofollow noreferrer">https://wiki.jenkins.io/display/JENKINS/Kubernetes+Cli+Plugin</a>
This is an example syntax for Jenkins scripted piepline:</p>

<p>Example:</p>

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

<p>And as you can see it does not accept anything for <code>namespace</code></p>

<p>This is an example production context with namespace, which I'm using:</p>

<pre><code>$ kubectl config get-contexts 
CURRENT   NAME             CLUSTER                           AUTHINFO                          NAMESPACE
*         aws-production   cluster.example.com   cluster.example.com       aws-production
</code></pre>

<p>And this is a result of running that step:
<a href="https://i.stack.imgur.com/XTj3W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XTj3W.jpg" alt="enter image description here"></a></p>

<p>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?</p>

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

<p>Manually forcing a config, doesn't help in this case too;</p>

<p><code>kubectl config use-context aws-production --namespace=aws-production --kubeconfig=/home/jenkins/.kube/config</code></p>

<p>Thanks to help from official Jenkins IRC channel, solution below.</p>

<p>Solution:
You have to pass raw .kube/config file as a <code>credentialsId</code>.</p>

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

<p>withKubeConfig([<code>credentialsId: 'file-aws-config'</code>, [..]]) ...</p>
