When we create a service account, a signed bearer token will be automatically created by the Kubernetes service account admission controller plugin. We can use that service account token to authenticate a user.
Let's try creating a service account named myaccount in the chapter5 namespace:
// the configuration file of service account object
# cat service-account.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: myaccount
namespace: chapter5
// create myaccount
# kubectl create -f service-account.yaml
serviceaccount/myaccount created
In Chapter 9, Continuous Delivery, in the example in which we demonstrated how to deploy my-app, we created a namespace named cd, and used get-sa-token.sh script (https://github.com/PacktPublishing/DevOps-with-Kubernetes-Second-Edition/blob/master/chapter9/9-2_service-account-for-ci-tool/utils/push-cd/get-sa-token.sh) to export the token for us:
// export ca.crt and sa.token from myaccount in namespace chapter5
# sh ./chapter9/9-2_service-account-for-ci-tool/utils/push-cd/get-sa-token.sh -n chapter5 -a myaccount
Then, we created a user named mysa via the kubectl config set-credentials <user> --token=$TOKEN command:
// CI_ENV_K8S_SA_TOKEN=`cat sa.token`
# kubectl config set-credentials mysa --token=${K8S_SA_TOKEN}
Next, we set the context to bind with a user and namespace:
// Here we set K8S_CLUSTER=gke_devops-with-kubernetes_us-central1-b_cluster
# kubectl config set-context myctxt --cluster=${K8S_CLUSTER} --user=mysa
Finally, we set our myctxt context as the default context:
// set the context to myctxt
# kubectl config use-context myctxt
When we send a request, the token will be verified by the API server, which checks whether the requester is eligible and is what it claims to be. Let's see if we can use this token to list the pods in the default namespace:
# kubectl get po
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:chapter5:myaccount" cannot list pods in the namespace "default"
Seems like something went wrong! This is because we haven't granted any permissions to this service account yet. We'll learn how to do this using Role and RoleBinding later in this chapter.