0
# RBAC and Security
1
2
Role-based access control management including roles, cluster roles, role bindings, service accounts, and security policies. Essential for implementing proper access controls and security policies in Kubernetes clusters with fine-grained permission management.
3
4
## Capabilities
5
6
### Role Management
7
8
Create and manage roles that define permissions within specific namespaces.
9
10
```python { .api }
11
class RbacAuthorizationV1Api:
12
def create_namespaced_role(
13
self,
14
namespace: str,
15
body: V1Role,
16
dry_run: str = None,
17
field_manager: str = None,
18
pretty: str = None
19
) -> V1Role:
20
"""Create a role in specified namespace."""
21
22
def list_namespaced_role(
23
self,
24
namespace: str,
25
pretty: str = None,
26
allow_watch_bookmarks: bool = None,
27
continue_: str = None,
28
field_selector: str = None,
29
label_selector: str = None,
30
limit: int = None,
31
resource_version: str = None,
32
timeout_seconds: int = None,
33
watch: bool = None
34
) -> V1RoleList:
35
"""List roles in specified namespace."""
36
37
def read_namespaced_role(
38
self,
39
name: str,
40
namespace: str,
41
pretty: str = None
42
) -> V1Role:
43
"""Read specified role."""
44
45
def patch_namespaced_role(
46
self,
47
name: str,
48
namespace: str,
49
body: object,
50
dry_run: str = None,
51
field_manager: str = None,
52
force: bool = None,
53
pretty: str = None
54
) -> V1Role:
55
"""Patch specified role."""
56
57
def delete_namespaced_role(
58
self,
59
name: str,
60
namespace: str,
61
body: V1DeleteOptions = None,
62
dry_run: str = None,
63
grace_period_seconds: int = None,
64
orphan_dependents: bool = None,
65
propagation_policy: str = None,
66
pretty: str = None
67
) -> V1Status:
68
"""Delete specified role."""
69
```
70
71
### Cluster Role Management
72
73
Create and manage cluster-wide roles that define permissions across the entire cluster.
74
75
```python { .api }
76
class RbacAuthorizationV1Api:
77
def create_cluster_role(
78
self,
79
body: V1ClusterRole,
80
dry_run: str = None,
81
field_manager: str = None,
82
pretty: str = None
83
) -> V1ClusterRole:
84
"""Create a cluster role."""
85
86
def list_cluster_role(
87
self,
88
pretty: str = None,
89
allow_watch_bookmarks: bool = None,
90
continue_: str = None,
91
field_selector: str = None,
92
label_selector: str = None,
93
limit: int = None,
94
resource_version: str = None,
95
timeout_seconds: int = None,
96
watch: bool = None
97
) -> V1ClusterRoleList:
98
"""List cluster roles."""
99
100
def read_cluster_role(
101
self,
102
name: str,
103
pretty: str = None
104
) -> V1ClusterRole:
105
"""Read specified cluster role."""
106
```
107
108
### Role Binding Management
109
110
Bind roles to users, groups, or service accounts to grant permissions.
111
112
```python { .api }
113
class RbacAuthorizationV1Api:
114
def create_namespaced_role_binding(
115
self,
116
namespace: str,
117
body: V1RoleBinding,
118
dry_run: str = None,
119
field_manager: str = None,
120
pretty: str = None
121
) -> V1RoleBinding:
122
"""Create a role binding in specified namespace."""
123
124
def list_namespaced_role_binding(
125
self,
126
namespace: str,
127
pretty: str = None,
128
allow_watch_bookmarks: bool = None,
129
continue_: str = None,
130
field_selector: str = None,
131
label_selector: str = None,
132
limit: int = None,
133
resource_version: str = None,
134
timeout_seconds: int = None,
135
watch: bool = None
136
) -> V1RoleBindingList:
137
"""List role bindings in specified namespace."""
138
139
def create_cluster_role_binding(
140
self,
141
body: V1ClusterRoleBinding,
142
dry_run: str = None,
143
field_manager: str = None,
144
pretty: str = None
145
) -> V1ClusterRoleBinding:
146
"""Create a cluster role binding."""
147
148
def list_cluster_role_binding(
149
self,
150
pretty: str = None,
151
allow_watch_bookmarks: bool = None,
152
continue_: str = None,
153
field_selector: str = None,
154
label_selector: str = None,
155
limit: int = None,
156
resource_version: str = None,
157
timeout_seconds: int = None,
158
watch: bool = None
159
) -> V1ClusterRoleBindingList:
160
"""List cluster role bindings."""
161
```
162
163
### Service Account Management
164
165
Create and manage service accounts for pod authentication and authorization.
166
167
```python { .api }
168
class CoreV1Api:
169
def create_namespaced_service_account(
170
self,
171
namespace: str,
172
body: V1ServiceAccount,
173
dry_run: str = None,
174
field_manager: str = None,
175
pretty: str = None
176
) -> V1ServiceAccount:
177
"""Create a service account in specified namespace."""
178
179
def list_namespaced_service_account(
180
self,
181
namespace: str,
182
pretty: str = None,
183
allow_watch_bookmarks: bool = None,
184
continue_: str = None,
185
field_selector: str = None,
186
label_selector: str = None,
187
limit: int = None,
188
resource_version: str = None,
189
timeout_seconds: int = None,
190
watch: bool = None
191
) -> V1ServiceAccountList:
192
"""List service accounts in specified namespace."""
193
194
def read_namespaced_service_account(
195
self,
196
name: str,
197
namespace: str,
198
pretty: str = None
199
) -> V1ServiceAccount:
200
"""Read specified service account."""
201
```
202
203
## Resource Models
204
205
### V1Role
206
```python { .api }
207
class V1Role:
208
api_version: str # "rbac.authorization.k8s.io/v1"
209
kind: str # "Role"
210
metadata: V1ObjectMeta
211
rules: list # List of V1PolicyRule
212
```
213
214
### V1ClusterRole
215
```python { .api }
216
class V1ClusterRole:
217
api_version: str # "rbac.authorization.k8s.io/v1"
218
kind: str # "ClusterRole"
219
metadata: V1ObjectMeta
220
rules: list # List of V1PolicyRule
221
aggregation_rule: V1AggregationRule
222
```
223
224
### V1RoleBinding
225
```python { .api }
226
class V1RoleBinding:
227
api_version: str # "rbac.authorization.k8s.io/v1"
228
kind: str # "RoleBinding"
229
metadata: V1ObjectMeta
230
subjects: list # List of V1Subject
231
role_ref: V1RoleRef
232
```
233
234
### V1ClusterRoleBinding
235
```python { .api }
236
class V1ClusterRoleBinding:
237
api_version: str # "rbac.authorization.k8s.io/v1"
238
kind: str # "ClusterRoleBinding"
239
metadata: V1ObjectMeta
240
subjects: list # List of V1Subject
241
role_ref: V1RoleRef
242
```
243
244
### V1ServiceAccount
245
```python { .api }
246
class V1ServiceAccount:
247
api_version: str # "v1"
248
kind: str # "ServiceAccount"
249
metadata: V1ObjectMeta
250
secrets: list # List of V1ObjectReference
251
image_pull_secrets: list # List of V1LocalObjectReference
252
automount_service_account_token: bool
253
```
254
255
### V1PolicyRule
256
```python { .api }
257
class V1PolicyRule:
258
verbs: list # ["get", "list", "create", "update", "patch", "delete"]
259
api_groups: list # ["", "apps", "extensions"]
260
resources: list # ["pods", "deployments", "services"]
261
resource_names: list # Specific resource names
262
non_resource_urls: list # Non-resource URLs like /healthz
263
```
264
265
### V1Subject
266
```python { .api }
267
class V1Subject:
268
kind: str # "User", "Group", "ServiceAccount"
269
name: str
270
namespace: str # For ServiceAccount subjects
271
api_group: str # "rbac.authorization.k8s.io" for User/Group
272
```
273
274
### V1RoleRef
275
```python { .api }
276
class V1RoleRef:
277
api_group: str # "rbac.authorization.k8s.io"
278
kind: str # "Role" or "ClusterRole"
279
name: str
280
```
281
282
## Usage Examples
283
284
### Creating a Role
285
286
```python
287
from kubernetes import client, config
288
289
config.load_kube_config()
290
rbac_api = client.RbacAuthorizationV1Api()
291
292
# Define role with specific permissions
293
role_manifest = {
294
"apiVersion": "rbac.authorization.k8s.io/v1",
295
"kind": "Role",
296
"metadata": {
297
"name": "pod-reader",
298
"namespace": "default"
299
},
300
"rules": [{
301
"apiGroups": [""],
302
"resources": ["pods"],
303
"verbs": ["get", "list"]
304
}, {
305
"apiGroups": [""],
306
"resources": ["pods/log"],
307
"verbs": ["get"]
308
}]
309
}
310
311
# Create the role
312
try:
313
role = rbac_api.create_namespaced_role(
314
namespace="default",
315
body=role_manifest
316
)
317
print(f"Role created: {role.metadata.name}")
318
except client.ApiException as e:
319
print(f"Failed to create role: {e}")
320
```
321
322
### Creating a Cluster Role
323
324
```python
325
from kubernetes import client, config
326
327
config.load_kube_config()
328
rbac_api = client.RbacAuthorizationV1Api()
329
330
# Define cluster role with node management permissions
331
cluster_role_manifest = {
332
"apiVersion": "rbac.authorization.k8s.io/v1",
333
"kind": "ClusterRole",
334
"metadata": {
335
"name": "node-manager"
336
},
337
"rules": [{
338
"apiGroups": [""],
339
"resources": ["nodes"],
340
"verbs": ["get", "list", "patch", "update"]
341
}, {
342
"apiGroups": [""],
343
"resources": ["nodes/status"],
344
"verbs": ["get", "update"]
345
}, {
346
"apiGroups": ["metrics.k8s.io"],
347
"resources": ["nodes", "pods"],
348
"verbs": ["get", "list"]
349
}]
350
}
351
352
# Create cluster role
353
cluster_role = rbac_api.create_cluster_role(body=cluster_role_manifest)
354
print(f"Cluster role created: {cluster_role.metadata.name}")
355
```
356
357
### Creating Service Account and Role Binding
358
359
```python
360
from kubernetes import client, config
361
362
config.load_kube_config()
363
v1 = client.CoreV1Api()
364
rbac_api = client.RbacAuthorizationV1Api()
365
366
# Create service account
367
service_account = {
368
"apiVersion": "v1",
369
"kind": "ServiceAccount",
370
"metadata": {
371
"name": "app-service-account",
372
"namespace": "default"
373
}
374
}
375
376
sa = v1.create_namespaced_service_account(
377
namespace="default",
378
body=service_account
379
)
380
print(f"Service account created: {sa.metadata.name}")
381
382
# Create role binding to bind role to service account
383
role_binding = {
384
"apiVersion": "rbac.authorization.k8s.io/v1",
385
"kind": "RoleBinding",
386
"metadata": {
387
"name": "app-pod-reader-binding",
388
"namespace": "default"
389
},
390
"subjects": [{
391
"kind": "ServiceAccount",
392
"name": "app-service-account",
393
"namespace": "default"
394
}],
395
"roleRef": {
396
"kind": "Role",
397
"name": "pod-reader",
398
"apiGroup": "rbac.authorization.k8s.io"
399
}
400
}
401
402
rb = rbac_api.create_namespaced_role_binding(
403
namespace="default",
404
body=role_binding
405
)
406
print(f"Role binding created: {rb.metadata.name}")
407
```
408
409
### Creating Cluster Role Binding
410
411
```python
412
from kubernetes import client, config
413
414
config.load_kube_config()
415
rbac_api = client.RbacAuthorizationV1Api()
416
417
# Bind cluster role to user
418
cluster_role_binding = {
419
"apiVersion": "rbac.authorization.k8s.io/v1",
420
"kind": "ClusterRoleBinding",
421
"metadata": {
422
"name": "node-manager-binding"
423
},
424
"subjects": [{
425
"kind": "User",
426
"name": "admin@mycompany.com",
427
"apiGroup": "rbac.authorization.k8s.io"
428
}, {
429
"kind": "ServiceAccount",
430
"name": "node-operator",
431
"namespace": "kube-system"
432
}],
433
"roleRef": {
434
"kind": "ClusterRole",
435
"name": "node-manager",
436
"apiGroup": "rbac.authorization.k8s.io"
437
}
438
}
439
440
crb = rbac_api.create_cluster_role_binding(body=cluster_role_binding)
441
print(f"Cluster role binding created: {crb.metadata.name}")
442
```
443
444
### Creating Comprehensive RBAC Setup
445
446
```python
447
from kubernetes import client, config
448
449
config.load_kube_config()
450
v1 = client.CoreV1Api()
451
rbac_api = client.RbacAuthorizationV1Api()
452
453
def create_rbac_setup(namespace, app_name, permissions):
454
"""Create complete RBAC setup for an application."""
455
456
# 1. Create service account
457
service_account = {
458
"apiVersion": "v1",
459
"kind": "ServiceAccount",
460
"metadata": {
461
"name": f"{app_name}-sa",
462
"namespace": namespace,
463
"labels": {"app": app_name}
464
}
465
}
466
467
sa = v1.create_namespaced_service_account(
468
namespace=namespace,
469
body=service_account
470
)
471
print(f"✓ Created service account: {sa.metadata.name}")
472
473
# 2. Create role with specified permissions
474
role = {
475
"apiVersion": "rbac.authorization.k8s.io/v1",
476
"kind": "Role",
477
"metadata": {
478
"name": f"{app_name}-role",
479
"namespace": namespace,
480
"labels": {"app": app_name}
481
},
482
"rules": permissions
483
}
484
485
r = rbac_api.create_namespaced_role(
486
namespace=namespace,
487
body=role
488
)
489
print(f"✓ Created role: {r.metadata.name}")
490
491
# 3. Create role binding
492
role_binding = {
493
"apiVersion": "rbac.authorization.k8s.io/v1",
494
"kind": "RoleBinding",
495
"metadata": {
496
"name": f"{app_name}-binding",
497
"namespace": namespace,
498
"labels": {"app": app_name}
499
},
500
"subjects": [{
501
"kind": "ServiceAccount",
502
"name": f"{app_name}-sa",
503
"namespace": namespace
504
}],
505
"roleRef": {
506
"kind": "Role",
507
"name": f"{app_name}-role",
508
"apiGroup": "rbac.authorization.k8s.io"
509
}
510
}
511
512
rb = rbac_api.create_namespaced_role_binding(
513
namespace=namespace,
514
body=role_binding
515
)
516
print(f"✓ Created role binding: {rb.metadata.name}")
517
518
return sa, r, rb
519
520
# Define permissions for a monitoring application
521
monitoring_permissions = [{
522
"apiGroups": [""],
523
"resources": ["pods", "services", "endpoints"],
524
"verbs": ["get", "list", "watch"]
525
}, {
526
"apiGroups": [""],
527
"resources": ["configmaps"],
528
"verbs": ["get", "list"]
529
}, {
530
"apiGroups": ["apps"],
531
"resources": ["deployments", "replicasets"],
532
"verbs": ["get", "list", "watch"]
533
}]
534
535
# Create RBAC setup
536
sa, role, binding = create_rbac_setup(
537
"monitoring",
538
"prometheus",
539
monitoring_permissions
540
)
541
```
542
543
### Working with Built-in Cluster Roles
544
545
```python
546
from kubernetes import client, config
547
548
config.load_kube_config()
549
rbac_api = client.RbacAuthorizationV1Api()
550
551
# List built-in cluster roles
552
cluster_roles = rbac_api.list_cluster_role()
553
554
print("Built-in cluster roles:")
555
builtin_roles = []
556
for role in cluster_roles.items:
557
if role.metadata.name.startswith('system:') or role.metadata.name in [
558
'admin', 'edit', 'view', 'cluster-admin'
559
]:
560
builtin_roles.append(role.metadata.name)
561
562
for role_name in sorted(builtin_roles):
563
print(f" - {role_name}")
564
565
# Use built-in 'view' role for read-only access
566
readonly_binding = {
567
"apiVersion": "rbac.authorization.k8s.io/v1",
568
"kind": "RoleBinding",
569
"metadata": {
570
"name": "developers-readonly",
571
"namespace": "development"
572
},
573
"subjects": [{
574
"kind": "Group",
575
"name": "developers",
576
"apiGroup": "rbac.authorization.k8s.io"
577
}],
578
"roleRef": {
579
"kind": "ClusterRole",
580
"name": "view",
581
"apiGroup": "rbac.authorization.k8s.io"
582
}
583
}
584
585
rb = rbac_api.create_namespaced_role_binding(
586
namespace="development",
587
body=readonly_binding
588
)
589
print(f"✓ Created read-only binding: {rb.metadata.name}")
590
```
591
592
### Authorization Checking
593
594
```python
595
from kubernetes import client, config
596
597
config.load_kube_config()
598
auth_api = client.AuthorizationV1Api()
599
600
def can_i(verb, resource, namespace=None, group="", name=None):
601
"""Check if current user can perform action on resource."""
602
603
resource_attributes = {
604
"verb": verb,
605
"group": group,
606
"resource": resource
607
}
608
609
if namespace:
610
resource_attributes["namespace"] = namespace
611
if name:
612
resource_attributes["name"] = name
613
614
# Create SelfSubjectAccessReview
615
access_review = {
616
"apiVersion": "authorization.k8s.io/v1",
617
"kind": "SelfSubjectAccessReview",
618
"spec": {
619
"resourceAttributes": resource_attributes
620
}
621
}
622
623
result = auth_api.create_self_subject_access_review(body=access_review)
624
return result.status.allowed
625
626
# Check permissions
627
permissions_to_check = [
628
("get", "pods", "default"),
629
("create", "deployments", "default", "apps"),
630
("delete", "services", "production"),
631
("get", "nodes", None) # Cluster-scoped
632
]
633
634
print("Permission check results:")
635
for check in permissions_to_check:
636
verb, resource = check[:2]
637
namespace = check[2] if len(check) > 2 else None
638
group = check[3] if len(check) > 3 else ""
639
640
allowed = can_i(verb, resource, namespace, group)
641
status = "✓ ALLOWED" if allowed else "✗ DENIED"
642
location = f"in {namespace}" if namespace else "cluster-wide"
643
print(f" {verb} {resource} {location}: {status}")
644
```
645
646
### Pod Security Context
647
648
```python
649
from kubernetes import client, config
650
651
config.load_kube_config()
652
v1 = client.CoreV1Api()
653
654
# Create pod with security context
655
secure_pod = {
656
"apiVersion": "v1",
657
"kind": "Pod",
658
"metadata": {
659
"name": "secure-pod",
660
"namespace": "default"
661
},
662
"spec": {
663
"serviceAccountName": "app-service-account",
664
"securityContext": {
665
"runAsNonRoot": True,
666
"runAsUser": 1000,
667
"runAsGroup": 1000,
668
"fsGroup": 1000,
669
"seccompProfile": {
670
"type": "RuntimeDefault"
671
}
672
},
673
"containers": [{
674
"name": "app",
675
"image": "nginx:1.20",
676
"securityContext": {
677
"allowPrivilegeEscalation": False,
678
"readOnlyRootFilesystem": True,
679
"capabilities": {
680
"drop": ["ALL"],
681
"add": ["NET_BIND_SERVICE"]
682
}
683
},
684
"volumeMounts": [{
685
"name": "tmp-volume",
686
"mountPath": "/tmp"
687
}, {
688
"name": "cache-volume",
689
"mountPath": "/var/cache/nginx"
690
}]
691
}],
692
"volumes": [{
693
"name": "tmp-volume",
694
"emptyDir": {}
695
}, {
696
"name": "cache-volume",
697
"emptyDir": {}
698
}]
699
}
700
}
701
702
# Create secure pod
703
pod = v1.create_namespaced_pod(namespace="default", body=secure_pod)
704
print(f"✓ Created secure pod: {pod.metadata.name}")
705
print(f" Running as user: {pod.spec.security_context.run_as_user}")
706
print(f" Non-root: {pod.spec.security_context.run_as_non_root}")
707
```