Constraint负责通知Gatekeeper,admin想要一个什么样的template
Constraint使用 K8sRequiredLabels 来约束上文中的模版,以便于确保 gatekeeper 标签被定义到所有namespace上
可认为是对某一个 ConstraintTemplate 的实例化,其中对 ConstraintTemplate 的未指定参数进行了具体的配置。
注意spec.match字段,它定义了 一个指定的约束 将要被应用到的 目标的范围
Note the match field, which defines the scope of objects to which a given constraint will be applied.
支持的匹配项目:
kinds:接受一个对象列表,包含 apiGroups和 kinds,用来指定 约束将应用到的 对象组/种类的字段。如果指定了多个对象,只要满足其中一个就会被匹配
only one match is needed for the resource to be in scope.
目标范围:允许 * ,Cluster 或者 Namespaced
此外还有:
namespaces:指定ns列表
excludedNamespaces:指定ns排除列表
labelSelector
namespaceSelector
注意:
如果定义了多个matcher,则匹配资源必须满足所有顶级matcher
空matcher匹配所有
namespaces, excludedNamespaces, 和 namespaceSelector 将会匹配上没有ns所属的资源,为了避免这种情况,注意指定Namespace范围。
部署
kubectl apply -f ConstraintV1Beta1.yaml kubectl get constraint 测试deployment apiVersion: apps/v1 kind: Deployment metadata: creationTimestamp: null name: nginx namespace: depl spec: replicas: 0 selector: matchLabels: io/os: linux template: metadata: labels: io/os: linux spec: containers: - image: nginx:latest name: nginxshell脚本:
#!/bin/sh deployFile=nginx-deployment.yaml echo echo echo kubectl config use-context deploy kubectl apply -f ${deployFile} -n depl && kubectl delete -f ${deployFile} -n depl echo -e "\n\n\n" kubectl config use-context kubernetes-admin@kubernetes实验结果:
root@master:~/OPAtest/MyTest# ./test.sh Switched to context "deploy". Error from server ([updatelimit-for-depl] %%%%%%%%%%%%%%%%%%%%%%%%%% Changes are only allowed on [Monday] or [Wednesday]. ): error when creating "nginx-deployment.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [updatelimit-for-depl] %%%%%%%%%%%%%%%%%%%%%%%%%% Changes are only allowed on [Monday] or [Wednesday].参考资料:
用户与角色绑定:https://zhuanlan.zhihu.com/p/43237959