[k8s] Service Account ============= ###### tags: `kubernetes` ## Create a read-only Service Account that has access to limited default namespace only. ### 1. Create a service account ```shell= kubectl create serviceaccount deploy-robot ``` ### 2. Create a role with get, list, and watch permission on default namespace ```yaml= kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: deploy-robot rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch"] ``` ### 3. Create role binding to bind the above role with the service account. ```yaml= kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: deploy-robot subjects: - kind: ServiceAccount name: deploy-robot roleRef: kind: Role name: deploy-robot apiGroup: rbac.authorization.k8s.io ``` ### 4. create secret > [color=orange] **secret type:** ***kubernetes.io/service-account-token***, and with correct ***annotation*** ```yaml= apiVersion: v1 kind: Secret metadata: name: deploy-robot-secret annotations: kubernetes.io/service-account.name: deploy-robot type: kubernetes.io/service-account-token ``` ### 5. Get the token for the service account from secrets ```shell= TOKEN=$(kubectl describe secrets "$(kubectl describe serviceaccount deploy-robot -n default| grep -i Tokens | awk '{print $2}')" -n default | grep token: | awk '{print $2}') ``` ### 6. Set the token in config credentials ```shell= kubectl config set-credentials deploy-robot --token=$TOKEN ``` ### 7. Set the context in Kube config ```shell= kubectl config set-context deploy-robot --cluster=${NAME_OF_YOUR_CLUSTER} --user=deploy-robot ``` ### 8. Set the current context to use the new podreader context ```shell= kubectl config use-context deploy-robot ```