Service accounts provide an identity to pods running in a cluster. Unlike user accounts which are managed by an external entity and are intended for humans, service accounts are made to be used by Pods.
Pods have a token that is automatically mounted on a volume that can be used to authenticate requests. Every namespace also has a default service account token which has no additional permissions than an unauthenticated user.
To learn more, check out the Service Accounts page.
To create a service account named sample-sa through kubectl:
kubectl create serviceaccount sample-sa
Similarly, we can also create the service account using a YAML file.
## sample-sa.yml
apiVersion: v1
kind: ServiceAccount
metadata:
name: sample-sa
And then apply:
kubectl apply -f sample-sa.yml
To configure a pod to use the service account:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
serviceAccountName: sample-sa
For every namespace in Kubernetes, a service account named default is automatically created. Each namespace has its own default service account.
Whenever a pod is created, the default service account and its created token are automatically mounted to that pod as a volume mount. Below is an example.
When a service account is created, it does the following:
This token can then be used as an authentication bearer token when making REST calls to the Kubernetes API.
Note that this JWT (token):
Tokens are auto-generated on Kubernetes 1.21 and below. However, this is changed on Kubernetes 1.24. A token needs to be created separately.
To create the token:
kubectl create token sample-sa
This way, the secret (token) and the service account are separate objects which needed to be associated with the pod during creation.
To create secrets with non-expiring tokens, create the secret object and then define the service account name in the annotations.
apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
name: mysecret
annotations:
kubernetes.io/service-account.name: myserviceaccount