您可以使用名为Kyverno的 Kubernetes 原生策略引擎:
Kyverno 在 Kubernetes 集群中作为动态准入控制器运行。Kyverno 从 kube-apiserver 接收验证和修改准入 webhook HTTP 回调,并应用匹配策略返回执行准入策略或拒绝请求的结果。
Kyverno 策略是可应用于整个集群 ( ClusterPolicy
) 或特定命名空间 ( Policy
) 的规则集合。
我将创建一个示例来说明它是如何工作的。
首先我们需要安装 Kyverno,您可以选择直接从最新版本清单安装 Kyverno,或者使用 Helm(请参阅:快速入门指南):
$ kubectl create -f https://raw.githubusercontent.com/kyverno/kyverno/main/definitions/release/install.yaml
安装成功后,我们来创建一个简单的ClusterPolicy
:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: labeling-policy
spec:
validationFailureAction: enforce
background: false
rules:
- name: deny-rule
match:
resources:
kinds:
- Pod
exclude:
clusterRoles:
- cluster-admin
preconditions:
- key: "{{request.object.metadata.labels.purpose}}"
operator: Equals
value: "*"
validate:
message: "Using purpose label is not allowed for you"
deny: {}
在上面的示例中,只有使用cluster-admin
ClusterRole
才能修改带有 label 的 Pod purpose
。
假设我有两个用户(john
和dave
),但只john
链接到cluster-admin
ClusterRole
via ClusterRoleBinding
:
$ kubectl describe clusterrolebinding john-binding
Name: john-binding
Labels: <none>
Annotations: <none>
Role:
Kind: ClusterRole
Name: cluster-admin
Subjects:
Kind Name Namespace
---- ---- ---------
User john
最后,我们可以测试它是否按预期工作:
$ kubectl run test-john --image=nginx --labels purpose=test --as john
pod/test-john created
$ kubectl run test-dave --image=nginx --labels purpose=test --as dave
Error from server: admission webhook "validate.kyverno.svc" denied the request:
resource Pod/default/test-dave was blocked due to the following policies
labeling-policy:
deny-rule: Using purpose label is not allowed for you
$ kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
test-john 1/1 Running 0 32s purpose=test
在Kyverno Writing Policies 文档中可以找到更多带有详细解释的示例。