kuberneteskustomize

How to exclude a resource when using namespace in kustomization.yaml?


Kustomize thinks that runtime.cluster.x-k8s.io/v1alpha1 ExtensionConfig is namespaced. But it is not.

How to make kustomize not add namespace: ... to metadata of these resources?

Example, to reproduce:

extensionconfig.yaml

apiVersion: runtime.cluster.x-k8s.io/v1alpha1
kind: ExtensionConfig
metadata:
  name: my-extensionconfig

kustomization.yaml

resources:
- extensionconfig.yaml

namespace: foooo

output:

❯ kubectl kustomize  .
apiVersion: runtime.cluster.x-k8s.io/v1alpha1
kind: ExtensionConfig
metadata:
  name: my-extensionconfig
  namespace: foooo

The namespace "foooo" gets set, but this should not be done.

Related: How to call a Kustomize patch after namemspace transformation?


Solution

  • What you want isn't currently possible.

    The list of resources that Kustomize knows are cluster scoped is hard coded here. While there is a request to make this configurable at runtime, it was opened in 2018 and closed in 2020 due to lack of activity.

    Fortunately, If the resource is not namespaced, then the extraneous value for metadata.namespace isn't a problem; it will simply be ignored when you create resources.


    You can get what you want with a custom transformer, although this will require you to run kustomize with the --enable-alpha-plugins and --enable-exec flags.

    Create (for example) `scripts/extensionconfig-remove-namespace.sh:

    mkdir -p scripts
    cat > scripts/extensionsconfig-remove-namespace.sh <<EOF
    #!/bin/bash
    yq -y  '.items |= map(del(select(.kind == "ExtensionConfig").metadata.namespace))'
    EOF
    chmod 755 scripts/extensionsconfig-remove-namespace.sh
    

    Add the transformer to your kustomization.yaml:

    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization
    namespace: foo
    resources:
    - extensionconfig.yaml
    - service.yaml
    
    transformers:
      - |
        kind: StripNamespaceFromExtensionConfig
        apiVersion: example.com/v1
        metadata:
          name: strip-namespace
          annotations:
            config.kubernetes.io/function: |
              exec:
                path: ./scripts/extensionconfig-remove-namespace.sh
    

    And run kustomize like this:

    kustomize build --enable-alpha-plugins --enable-exec