Kubernetes Service Accounts
As a developer or a cluster admin, you interact with the Kubernetes
ServiceAccount is a Kubernetes object that allows an application running inside a
Pod to access the Kubernetes
apiserver. This is useful for applications that need to interact directly with the Kubernetes API, such as monitoring tools. A
ServiceAccount allows an application to talk to the
apiserver securely with the appropriate permissions.
ServiceAccount is defined as follows.
ServiceAccount itself is of little use unless you associate it with a set of roles. To do this you’ll need to create a
- apiGroups: [ "" ] # "" indicates the core API group
resources: [ "pods" ]
verbs: [ "get", "watch", "list" ]
Role describes the APIs that the
Role owner will have access to as well as resources and access to those resources. In this instance the
Role can get, watch and list pods.
To associate a
Role with a
ServiceAccount, you need to create a
RoleBinding linking the
pod-reader-role to the
sample-service-account is defined below.
- kind: ServiceAccount
name: pod-reader-role # this must match the name of the Role you want to bind to
Finally, we can create a
Pod that references the
ServiceAccount by setting the
serviceAccountName in the
Pod spec as follows.
- name: service-account-pod
command: [ 'sh', '-c', 'echo container started & sleep 3600' ]
Next, create the various objects on the cluster as follows.
Pod starts you can exec into the container and get the
ServiceAccount token from
/var/run/secrets/kubernetes.io/serviceaccount/token. You can then use the token to make an authenticated call to the Kubernetes API.
RoleBinding created earlier, we have the required privileges to retrieve a list of Pods from the API.
cat index.html we’ll see a list of
The sample code for these notes is available here.