<p>I am configuring Jenkins on Kubernetes system. It works fine to build. But in order to deploy, we need to call kubectl or helm. Currently, I am using</p>

<ul>
<li>lachlanevenson/k8s-kubectl:v1.8.8</li>
<li>lachlanevenson/k8s-helm:latest</li>
</ul>

<p>It is fail and throw exception: "Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:jenkins:default" cannot list pods in the namespace "jenkins""</p>

<p>The jenkins script is simple:</p>

<pre><code>def label = "worker-${UUID.randomUUID().toString()}"

podTemplate(label: label,containers: [
  containerTemplate(name: 'kubectl', image: 'lachlanevenson/k8s-kubectl:v1.8.8', command: 'cat', ttyEnabled: true)
],
volumes: [
  hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]){
  node(label) {
    stage('Run kubectl') {
        container('kubectl') {
            sh "kubectl get pods"
        }    
    }
  }
}
</code></pre>

<p>Could you please let me know what is wrong?</p>

<p>Thanks,</p>

<p>The Kubernetes (k8s) master, as of Kubernetes v1.8, by default implements <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac/" rel="nofollow noreferrer">role-based access control (RBAC)</a> security controls on accesses to its API. The RBAC controls limit access to the k8s API by your workloads to only those resources and methods which you have explicitly permitted.</p>

<p>You should create a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#role-v1-rbac-authorization-k8s-io" rel="nofollow noreferrer">role</a> which permits access to the <code>pod</code> resource's <code>list</code> verb (and any other resources you require<sup>1</sup>), create a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#serviceaccount-v1-core" rel="nofollow noreferrer">service account</a> object, and finally create a <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.11/#rolebinding-v1-rbac-authorization-k8s-io" rel="nofollow noreferrer">role binding</a> which assigns the role to the service account.</p>

<p>Finally, provide the service account to your Jenkins deployment by supplying its name in the <code>serviceAccountName</code> property of the Pod template. Ensure <code>automountServiceAccountToken</code> is <code>true</code> to have k8s install an API key into your Pod. Attempts to access the k8s API using the native k8s API wrappers and libraries should find this key and automatically authenticate your requests.</p>

<p><sup>1</sup><sub>If you are planning to make deployments from Jenkins, you will certainly require more than the ability to list Pods, as you will be required to mutate objects in the system. However, if you use Helm, it is Helm's Tiller pod which influences the downstream k8s objects for your deployments, so the set of permissions you require for the Helm Tiller and for Jenkins to communicate with the Tiller will vary.</sub></p>
