diff --git a/pkg/kubectl/resource/builder.go b/pkg/kubectl/resource/builder.go index 985cc63d8fe..04411ed3940 100644 --- a/pkg/kubectl/resource/builder.go +++ b/pkg/kubectl/resource/builder.go @@ -402,6 +402,7 @@ func (b *Builder) Do() *Result { if b.requireNamespace { helpers = append(helpers, RequireNamespace(b.namespace)) } + helpers = append(helpers, FilterNamespace()) r.visitor = NewDecoratedVisitor(r.visitor, helpers...) return r } diff --git a/pkg/kubectl/resource/visitor.go b/pkg/kubectl/resource/visitor.go index 368a44cfd27..23f9cf445ec 100644 --- a/pkg/kubectl/resource/visitor.go +++ b/pkg/kubectl/resource/visitor.go @@ -384,6 +384,17 @@ func UpdateObjectNamespace(info *Info) error { return nil } +// FilterNamespace omits the namespace if the object is not namespace scoped +func FilterNamespace() VisitorFunc { + return func(info *Info) error { + if info.Mapping.Scope.Name() != meta.RESTScopeNameNamespace { + info.Namespace = "" + UpdateObjectNamespace(info) + } + return nil + } +} + // SetNamespace ensures that every Info object visited will have a namespace // set. If info.Object is set, it will be mutated as well. func SetNamespace(namespace string) VisitorFunc {