Basics
Add users with limited rights
This article will teach you how to create service accounts for managing resources in a single namespace. To get started, you need to have kubectl installed on your computer. If you haven’t installed the application yet, use our article: Kubectl. How to connect to Kubernetes cluster.
Basics you need to know
What are service accounts? We not only use them to allow pods to read and use Kubernetes API objects, but also to create a kubeconfig file, which grants access to the Kubernetes objects limited to the namespace for any user or service. To learn more about Service Accounts, please refer to the Kubernetes documentation: Managing Service Accounts.
What is a namespace? In Kubernetes, the namespace is a method of organizing and isolating groups of resources within a single cluster. This helps various teams, projects, or customers to share the Kubernetes cluster. For more information about namespaces, you can refer to the Kubernetes documentation: Namespaces.
How to add users with limited rights in Kubernetes
1. Create a namespace using kubectl. Enter the following command:
kubectl create ns test-namespace
2. Then, create a service account. You can follow the template below:
cat <<EOF | kubectl apply -f - apiVersion: v1
kind: ServiceAccount
metadata:
name: test-serviceaccount
namespace: test-namespace
–--
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-serviceaccount-rolebinding
namespace: test-namespace
subjects:
- Kind: ServiceAccount
name: test-serviceaccount
roleRef:
kind: ClusterRole
name: edit
apiGroup: rbac.authorization.k8s.io
EOF
In this template, we used our own values:
- Namespace is test-namespace
- Service Account name is test-serviceaccount
- Role Binding name is test-serviceaccount-rolebinding
You should replace them with your own values.
3. Get its token. Locate secret name like test-serviceaccount-token-{% random characters here %} (with type kubernetes.io/service-account-token).
kubectl -n test-namespace get secret
Then extract the token from the secret and encode it in this method. The token can be stored in the file for easier future use.
kubectl -n test-namespace get secret test-serviceaccount-token-{% some random characters here%} -o jsonpath="{.data.token}" | base64 -d
4. Prepare your Kubernetes config file for the service account. To do this, edit the file’s content according to the screenshots below.
Before:
After:
5. To check the correctness of the created service account and Kubernetes configuration file follow the steps below.
Use your newly created kubeconfig file to connect to the kubernetes cluster.
Perform actions on dedicated (to the service account) and other namespaces. The result should be fail (F) or success (S).
If so, the service account and kubeconfig can be now considered as correctly created.