kubernetes: kubectl apply: prune should ignore no-namespaced resource if -n is not empty

kubectl apply with below yaml and follow below prune command.

**
namespace sandbox
**
---
apiVersion: v1
kind: Service
metadata:
  annotations:
    environment: sandbox
    provider: kustomize
  labels:
    app: nginx
  name: nginx
  namespace: sandbox
spec:
  ports:
  - port: 80
  selector:
    app: nginx
  type: NodePort

seems I have the same problem. save this to a file named a.yaml

apiVersion: v1
kind: Service
metadata:
  annotations:
    environment: sandbox
    provider: kustomize
  labels:
    app: nginx
  name: nginx
  namespace: sandbox
spec:
  ports:
  - port: 80
  selector:
    app: nginx
  type: NodePort

And run kubectl apply --prune --dry-run=client --all -n sandbox -f a.yaml, the results

service/nginx created (dry run)
namespace/cattle-system pruned (dry run)

I have no idea why it want to prune the namespace/cattle-system.

_Originally posted by @wd in https://github.com/kubernetes/kubernetes/issues/66430#issuecomment-708922169_

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 25 (18 by maintainers)

Most upvoted comments

I’d like to work on this issue /assign

https://github.com/kubernetes/kubernetes/pull/110907 was merged in v1.26

  • kubectl apply: warning that kubectl will ignore no-namespaced resource pv & namespace in a future release if the namespace is specified and allowlist is not specified

https://github.com/kubernetes/kubernetes/blob/3ce7cdda1ff61d2bbe31114accceb2343358325f/staging/src/k8s.io/kubectl/pkg/util/prune/prune.go#L66-L73

@m-Bilal I started with that. I will share what am I planning and other research, we can collaborate on this. You can help me with optimizations and feedback. If that sounds good to you.

Hi @pacoxu

I was looking at the test cases for prune inside apply_test.go, seems like it never goes inside the pruning logic. https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_test.go#L584-L632 as we are not setting up fakeDynamicClient to handle list request for the resource under test.

Should we fix the test case as well? I have tried to setup the fakeDynamicClient and register some reactor to respond to list and delete requests. With some data alterations able to get the prune logic executed.