{{- if and (.Values.cluster_config.external_kubectl_access.enabled) (.Values.kyverno.enabled) }}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: generate-external-admin-rolebinding
  annotations:
    policies.kyverno.io/title: Generate cluster-Admin rolebinding customer namespaces
    policies.kyverno.io/category: other
    policies.kyverno.io/severity: medium
    policies.kyverno.io/subject: Namespace, RoleBinding
    kyverno.io/kyverno-version: 1.7.0
    policies.kyverno.io/minversion: 1.7.0
    kyverno.io/kubernetes-version: "1.23"
    policies.kyverno.io/description: >-
      Customers should not have full admin permissions on their own namespaces.  
      This policy will generate a RoleBinding, binding their group_id to 
      the Cluster-Admin clusterrole. This will still only apply to the namespace as
      the resource is a rolebinding, not clusterrolebinding.
      This policy should not trigger on any namespaces with label component=sys
spec:
  generateExistingOnPolicyUpdate: true
  rules:
  - name: generate-rolebinding
    match:
      any:
      - resources:
          kinds:
          - Namespace
    exclude:
      any:
      - resources:
          kinds:
          - Namespace
          selector:
            matchLabels:
              component: sys
    generate:
      apiVersion: rbac.authorization.k8s.io/v1
      kind: RoleBinding
      name: external-ns-admin
      namespace: {{` "{{request.object.metadata.name}}" `}}
      synchronize: true
      data:
        metadata:
          labels:
            created-by: kyverno
        roleRef:
          apiGroup: rbac.authorization.k8s.io
          kind: ClusterRole
          name: cluster-admin
        subjects:
        - apiGroup: rbac.authorization.k8s.io
          kind: Group
          name: {{ .Values.cluster_config.external_kubectl_access.admin_group }}
{{- end }}
