Service Accounts in K8s (Kubernetes)

In this post let’s try understanding

  • What is a service account in K8s
  • Why do we need it?
  • Example on the same

K8s applications run in Pods. Pods usually need access to resources from cloud vendors like aws, gcloud, azure, etc.

Pods requiring resources

Pod’s life is not simple 😃, it is ephemeral in nature, it might belong to different namespaces, might come up and down(causing change in properties) etc. So one would have to inject the IAM-Role at a place where pods are born, so any new pods coming up would have this property available to them(like deployment manifest).

But the catch here is IAM-Role is an aws concept, and we cannot use the same in K8s constructs directly(these are two different domains). Thats where Service Accounts come in. Service account is a K8s construct and hence can be associated with a deployment manifest.

Service accounts

IAM OIDC provider helps facilitate this at the cluster level(set it up once & one should be good to go).

When a service account is not used, default one is used.

MyK8sCluster> kubectl get sa
default 1 191d

kubectl get sa -A => Provides all service accounts in a cluster
# sample_sa.yml
apiVersion: v1
kind: ServiceAccount
name: sample-service-account
namespace: sample-ns
MyK8sCluster> kubectl apply -f sa.yml
serviceaccount/sample-service-account created
MyK8sCluster> kubectl get sa --namespace=sample-ns
default 1 111s
sample-service-account 1 82s

Service accounts are restricted to the namespace they are created in. Clusterrole (kubectl get clusterrole) are used for permissions related to an entire cluster.

To use service account in a pod, something like below can be used. This would provide my-pod all policies defined by service account sample-service-account . See how the namespace should be in the same namespace as the one in which the service account was created in.

apiVersion: v1
kind: Pod
name: my-pod
namespace: sample-ns
serviceAccountName: sample-service-account
- name : "mycontainer"
image: nginx

There are more concepts here like ClusterRoleBinding, Role, ClusterRole etc. which are related to service accounts in K8s, which we can look into in a followup article. Hope this was useful in explaining service accounts in K8s. Would love to hear your feedback in comments. Till next time ciao and stay safe! 👋

whoami >> Slack, Prev — Springpath (Acquired by Cisco), VMware, Build & Release, Test-Infra, Test Automation, Devops and Cybersecurity Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store