Score:0

Using a variable in the namespace of a generated resource

au flag

I've created a policy that generates Services for every Deployment in a namespace. The one thing I can't figure out is that it's a Policy rather than a ClusterPolicy and I want to make the namespace attribute dynamic. (Because the policy is part of a Kustomize overlay that's used to define qa and prod environments.) It doesn't seem to be intepreting the variables in this field prior to validating the policy though:

admission webhook "validate-policy.kyverno.svc" denied the request: path: spec.rules[create-service]: a namespaced policy cannot generate resources in other namespaces, expected: bradmac-integration-platform, received: {{ request.object.metadata.namespace }}

apiVersion: kyverno.io/v1
kind: Policy
metadata:
  name: auto-generate-services
  annotations:
    policies.kyverno.io/title: Autogenerate services for deployments
    policies.kyverno.io/category: Argo
    policies.kyverno.io/severity: medium
    policies.kyverno.io/subject: Deployment, Service
    policies.kyverno.io/description: >-
      This policy generates `Service`s automatically based on `Deployment`s.
spec:
  generateExistingOnPolicyUpdate: true
  rules:
    - name: create-service
      match:
        all:
          - resources:
              kinds:
                - Deployment
      generate:
        apiVersion: v1
        kind: Service
        name: "{{ regex_replace_all('-deploy', request.object.metadata.name, '') }}-service"
        namespace: "{{request.object.metadata.name}}" # <- this variable isn't being interpolated
        synchronize: true
        data:
          metadata:
            ownerReferences:
              - apiVersion: v1
                kind: Deployment
                name: "{{ request.object.metadata.name }}"
                uid: "{{request.object.metadata.uid}}"
          spec:
            selector:
              app: "{{ regex_replace_all('-deploy', request.object.metadata.name, '') }}"
            ports:
              - port: 80
                targetPort: 8085
                protocol: "TCP"
            type: ClusterIP

Anyone know of any workarounds so that this can work for whatever namespace the overlay places it in?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.