Use context: kubectl config use-context infra-prod

There is an existing Open Policy Agent + Gatekeeper policy to enforce that all Namespaces need to have label security-level set. Extend the policy constraint and template so that all Namespaces also need to set label management-team. Any new Namespace creation without these two labels should be prevented.

Write the names of all existing Namespaces which violate the updated policy into /opt/course/p2/fix-namespaces.


译文

使用上下文: kubectl config use-context infra-prod

有一个现有的Open Policy Agent + Gatekeeper策略来强制执行,所有Namespace需要设置标签 security-level 。扩展策略约束和模板,所有 Namespaces 也需要设置标签 management-team。阻止创建任何没有这两个标签的新命名空间。

将所有违反更新策略的现有 Namespace 的名称写入 /opt/course/p2/fix-namespaces 中。


解答

检查现有opa限制

k get crd
k get constraint

检查违规情况

k describe requiredlabels namespace-mandatory-labels

file

看到命名空间 sidecar-injector 有一处违规

k get ns --show-labels

file

当我们试图创建一个没有任何标签的命名空间的时候,提示OPA错误

k create ns test

file

编辑约束 添加另外一个标签

k edit requiredlabels namespace-mandatory-labels
# kubectl edit requiredlabels namespace-mandatory-labels
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: RequiredLabels
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"constraints.gatekeeper.sh/v1beta1","kind":"RequiredLabels","metadata":{"annotations":{},"name":"namespace-mandatory-labels"},"spec":{"match":{"kinds":[{"apiGroups":[""],"kinds":["Namespace"]}]},"parameters":{"labels":["security-level"]}}}
  creationTimestamp: "2020-09-14T19:29:53Z"
  generation: 1
  name: namespace-mandatory-labels
  resourceVersion: "3081"
  selfLink: /apis/constraints.gatekeeper.sh/v1beta1/requiredlabels/namespace-mandatory-labels
  uid: 2a51a291-e07f-4bab-b33c-9b8c90e5125b
spec:
  match:
    kinds:
    - apiGroups:
      - ""
      kinds:
      - Namespace
  parameters:
    labels:
    - security-level
    - management-team # add

检查

k get constrainttemplates

k edit constrainttemplates requiredlabels
# kubectl edit constrainttemplates requiredlabels
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
...
spec:
  crd:
    spec:
      names:
        kind: RequiredLabels
      validation:
        openAPIV3Schema:
          properties:
            labels:
              items: string
              type: array
  targets:
  - rego: |
      package k8srequiredlabels

      violation[{"msg": msg, "details": {"missing_labels": missing}}] {
        provided := {label | input.review.object.metadata.labels[label]}
        required := {label | label := input.parameters.labels[_]}
        missing := required - provided
        # count(missing) == 1 # 注释后添加下面一行
        count(missing) > 0    # 添加
        msg := sprintf("you must provide labels: %v", [missing])
      }
    target: admission.k8s.gatekeeper.sh

检查

k describe requiredlabels namespace-mandatory-labels

file

违规命名空间写入文件

# /opt/course/p2/fix-namespaces
sidecar-injector
jeffs-playground