Starting from Kubernetes version 1.24, the secrets for a service account are no longer created automatically. This can be a problem for developers who need to access the Kubernetes API server with the service account, for example, when working with pipelines. We had the issue when connection to vault. In this post, I will show you how to manually create a secret for a service account in Kubernetes.
Using kubectl create token to Create a Token
To generate a token to access the Kubernetes API server, you can use the kubectl create token command. This command will return a JWT token. Here's an example:
# creating service account
kubectl create sa pipeline
kubectl create token pipeline
kubectl create token pipeline --duration=999999h
Manually Creating a Secret for a Service Account
You can also manually create a secret for a service account by running the following commands:
kubectl create sa <serviceaccount-name>
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
name: <secretname>
annotations:
kubernetes.io/service-account.name: <serviceaccount-name>
type: kubernetes.io/service-account-token
EOF
It's important to note that if you look at the service account, it will not list the count of secrets. This can be a bit misleading, so keep this in mind.
➜ ~ kubectl get sa
NAME SECRETS AGE
default 0 231d
test-sa 0 18m
Deleting a Service Account
If you delete the service account, the assigned secret will also be deleted. Here's how you can delete a service account:
kubectl delete sa <serviceaccount-name>
➜ ~ k get sa
NAME SECRETS AGE
default 0 231d
test-sa 0 18m
➜ ~ k delete sa test-sa
serviceaccount "test-sa" deleted
➜ ~ k get secrets
No resources found in default namespace.
After deleting the service account, the assigned secret will no longer be listed in the Kubernetes namespace.
For more information on creating a secret for a service account in Kubernetes, check out the official Kubernetes documentation here.
Hopefully this post was useful to you.
Top comments (0)