Creating ServiceAccount Secrets in Kubernetes

Kubernetes ServiceAccount Secrets API Access

1 min read | by Jordi Prats

Starting Kubernetes 1.24, Secrets are not automatically generated when Service Accounts are created. Since we won't have a Secret generated when we create the ServiceAccount, how can we create ServiceAccount Secrets so that External Applications can access the Kubernetes API?

Assuming we create the sa-name ServiceAccount like this:

$ kubectl create sa sa-name
serviceaccount/sa-name created

We won't get any tokens:

$ kubectl get sa,secret
NAME                     SECRETS   AGE
serviceaccount/default   0         29s
serviceaccount/sa-name   0         6s

But we can request a new token by creating an empty secret with the kubernetes.io/service-account.name annotation:

cat <<"EOF" | kubectl apply -f -
apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
  name: demo
  annotations:
    kubernetes.io/service-account.name: sa-name
EOF

Kubernetes is going to populate the secret that we will be able to use with to access the Kubernetes API:

$ kubectl get secret demo -o json | jq '.data | keys[]'
"ca.crt"
"namespace"
"token"

Posted on 17/04/2023