Heyo,
In production Kubernetes environments, access control becomes critical when multiple services share the same cluster. I recently faced this exact scenario: a GKE cluster hosting multiple services across different namespaces, where a new team needed access to maintain and debug their service-but only their service.
The requirement was straightforward yet specific: grant external users the ability to exec into pods, view logs, and forward ports, but restrict this access to a single namespace within a single GKE cluster. No access to other clusters in the Google Cloud project, and no access to other namespaces.
The Solution
Achieving this granular access control requires combining Google Cloud IAM with Kubernetes RBAC (Role-Based Access Control). Here’s how to implement it:
Step 1: Tag Your GKE Cluster
First, apply a unique tag to your GKE cluster. This tag will serve as the identifier for IAM policies.
Step 2: Grant IAM Access via Tags
Add an IAM policy binding that grants users access to resources with your specific tag. The Kubernetes Engine Viewer role (roles/container.viewer) provides sufficient base permissions without granting excessive access.
Step 3: Create a Kubernetes ClusterRole
Define a ClusterRole that specifies the exact permissions needed:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: custom-access-role
rules:
- apiGroups: [""]
resources: ["pods", "pods/exec", "pods/attach", "pods/portforward", "pods/log"]
verbs: ["get", "list", "watch", "create"]
Note: While you could use a namespace-scoped Role, a ClusterRole offers better reusability if you need similar permissions for other namespaces later.
Step 4: Bind the Role to Users
Create a RoleBinding to connect the role to specific users and namespaces:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: custom-rolebinding
namespace: my-namespace
subjects:
- kind: User
name: myuser@gmail.com
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: custom-access-role
apiGroup: rbac.authorization.k8s.io
Apply both configurations using kubectl apply -f <filename>.
How It Works
This approach creates a two-layer security model:
- GCP IAM controls which clusters users can access using resource tags
- Kubernetes RBAC controls what users can do within the cluster and limits their scope to specific namespaces
The result is a secure, maintainable solution that grants teams the access they need without compromising the security of other services in your cluster.