Add a user to a Kubernetes cluster
Previously, an Kubernetes cluster environment was set up using Ansible. The current requirement is to add a user for daily management, restricted to a specific namespace. Below are the steps:
Kubernetes Users
In Kubernetes, there are two types of users: ServiceAccounts and regular users (User). ServiceAccounts are managed by Kubernetes, while regular users are typically managed externally. Kubernetes does not store user lists—meaning user creation, modification, or deletion must be handled externally, without interacting with the Kubernetes API. Although Kubernetes does not manage users directly, it can recognize the identity of users making API requests. In fact, every API request to Kubernetes must be associated with an identity (either a User or a ServiceAccount), allowing us to assign permissions within the cluster to specific users.
When Kubernetes receives API requests from users, it commonly uses one of three authentication methods: client certificates, static token files, or static password files. Here, we focus only on certificate-based authentication.
Generate User Certificate
Prepare a Certificate Signing Request (CSR) file, which will be signed by the Kubernetes CA. The default path for the Kubernetes API server’s CA is /etc/kubernetes/pki/. This process generates cicd-admin-key.pem (private key) and cicd-admin.pem (certificate). For details on generating CSR files, refer to: https://wnote.com/post/linux-openssl-issue-private-certificate/
The username passed in the CSR file is cicd-admin.
|
|
User Permission Control (RBAC)
Create Role
In Kubernetes, RBAC roles come in two types: Role and ClusterRole. A ClusterRole is a special kind of Role:
- A
Rolebelongs to a specific namespace; aClusterRoleapplies across the entire cluster, including all namespaces. - A
ClusterRolecan grant cluster-wide permissions (e.g., managingNoderesources) and can access resources across all namespaces (using--all-namespaces). By default, Kubernetes includes a built-inClusterRolenamedadmin, which is usually sufficient and doesn’t require manual creation.
Create a role named cicd-admin in the cicd namespace:
Bind User to Role
subjectsspecifies the account type, which can be eitherUserorServiceAccount. Here, we bind the usercicd-admin.roleRefdefines the role referenced by the RoleBinding.
Alternatively, use kubectl to create the binding:
|
|
Or bind the user to the default ClusterRole admin, which will limit the user’s permissions to the cicd namespace:
Client Configuration
Set Cluster Parameters
Set Client Authentication Parameters
Set Context Parameters
Set Default Context
|
|
Client Usage
Copy the kubeconfig file to override ~/.kube/config:
|
|
With this, the setup for adding a user and granting them authorized access to the Kubernetes cluster is complete.