Using ServiceAccounts in Kubernetes

Overview
ServiceAccounts in Kubernetes provide identities for processes running in Pods, enabling them to authenticate with the Kubernetes API server.
Documentation
Example ServiceAccount Creation
Here's how to create a ServiceAccount:
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-serviceaccount
automountServiceAccountToken: true
Steps to Create and Use ServiceAccounts
-
Create the ServiceAccount
Define your ServiceAccount in a YAML file as shown above. Save this file as
my-serviceaccount.yaml
. Apply it withkubectl apply -f my-serviceaccount.yaml
. -
Assign the ServiceAccount to a Pod
Specify the ServiceAccount in the Pod's specification. Example:
apiVersion: v1 kind: Pod metadata: name: my-pod spec: serviceAccountName: my-serviceaccount containers: - name: my-container image: nginx
Save this as
my-pod.yaml
and apply it withkubectl apply -f my-pod.yaml
. -
Location of the Mounted Token
The ServiceAccount token is automatically mounted at
/var/run/secrets/kubernetes.io/serviceaccount
in each container.This directory contains: -
token
: The ServiceAccount token. -ca.crt
: Certificate for TLS communication with the API server. -namespace
: The namespace of the Pod. -
Using the Token for API Authentication
Applications in the container can use the token for Kubernetes API server authentication. The token can be accessed at
/var/run/secrets/kubernetes.io/serviceaccount/token
.
Accessing the Kubernetes API from a Pod
Here’s how a container might use the token to communicate with the Kubernetes API.
apiVersion: v1
kind: Pod
metadata:
name: api-communicator-pod
spec:
serviceAccountName: my-serviceaccount
containers:
- name: api-communicator
image: busybox
command: ["sh", "-c", "curl -H \"Authorization: Bearer $(cat /var/run/secrets/kubernetes.io/serviceaccount/token)\" https://kubernetes.default.svc"]
Conclusion
ServiceAccounts in Kubernetes facilitate the secure operation of processes within Pods by providing a means of authenticating with the Kubernetes API server. The automatic mounting of ServiceAccount tokens into Pods simplifies the process of managing secure communications and access controls within a Kubernetes environment.