<p>I have a script that calls <code>kubectl -server $server --certificate-authority $ca --token $token get pod --all-namespaces</code> outside the cluster, where<code>$token</code> is from a service account <code>my-sa</code> (in namespace <code>my-ns</code>) with suitably restricted permissions under RBAC.</p>

<p>I now want to refactor this such that the script calls <code>kubectl --kubeconfig my-service.conf get pod --all-namespaces</code> instead, i.e. it should refer to a kubeconfig file instead of setting local parameters. This is in following Kubernetes' own conventions around its own kubeconfigs in <code>/etc/kubernetes</code>.</p>

<p>I've tried the following kubeconfig <code>my-service.conf</code>; <code>&lt;CA_DATA&gt;</code> is the base64-encoded content of <code>/etc/kubernetes/pki/ca.crt</code>, <code>&lt;SERVER&gt;</code> is same as <code>$server</code>, and <code>&lt;TOKEN&gt;</code> is same as <code>$token</code>:</p>

<pre><code>apiVersion: v1
kind: Config
clusters:
- cluster:
    certificate-authority-data: &lt;CA_DATA&gt;
    server: &lt;SERVER&gt;
  name: my-cluster 
contexts:
- context:
  name: default-context
  context:
    cluster: my-cluster
    user: default-user
current-context: default-context
users:
- name: my-service
  user:
    token: &lt;TOKEN&gt;
</code></pre>

<p><code>kubectl --kubeconfig /dev/null --server $server --certificate-authority /etc/kubernetes/pki/ca.crt --token $token get pods --all-namespaces</code> works on the command line, but <code>kubectl --kubeconfig my-service.conf get pod --all-namespaces</code> produces the following error message:</p>

<blockquote>
  <p>Error from server (Forbidden): pods is forbidden: User
  "system:anonymous" cannot list resource "pods" in API group "" at the
  cluster scope</p>
</blockquote>

<p>So there still be something wrong with the <a href="https://stackoverflow.com/questions/47770676/how-to-create-a-kubectl-config-file-for-serviceaccount">structure of my kubeconfig file</a>. Why did the client not <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/" rel="nofollow noreferrer">authenticate as</a> <code>system:serviceaccount:my-ns:my-sa</code>? What could be wrong?</p>

<p><strong>UPDATE</strong> I was wondering whether it was perhaps inappropriate to use service account tokens outside the cluster (Kubernetes' own kubeconfigs use client certificates instead). But then the <a href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/" rel="nofollow noreferrer">documentation</a> clearly states: "service account bearer tokens are perfectly valid to use outside the cluster".</p>

rookie099
<p>Your context config is referencing an inexistent credential...</p>

<p>Your credential is specified as <code>- name: my-service</code>, so your context should be:</p>

<pre><code>- context:
  name: default-context
  context:
    cluster: my-cluster
    user: my-service       # instead of default-user
</code></pre>
