Search code examples
kuberneteskubernetes-go-client

How to apply top level namespace using kubernetes go client


Using kubectl we can specify which namespace should we install the resources in, example -> kubectl apply -f abc.yaml -n mynamespace

this would ensure all my resources are creates in 'mynamespace'.

How do I achieve this using the Kubernetes Go client. I am looking for ways which DO NOT involve changing each and every helm/yaml and adding namespaces explicitly.


Solution

  • You can see how kubectl does it here: https://github.com/kubernetes/kubernetes/blob/fe3772890f650f9bcf020b43dc5a51fab0fa17f4/staging/src/k8s.io/cli-runtime/pkg/resource/helper.go#L240-L248

    func (m *Helper) createResource(c RESTClient, resource, namespace string, obj runtime.Object, options *metav1.CreateOptions) (runtime.Object, error) {
        return c.Post().
            NamespaceIfScoped(namespace, m.NamespaceScoped).
            Resource(resource).
            VersionedParams(options, metav1.ParameterCodec).
            Body(obj).
            Do(context.TODO()).
            Get()
    }
    

    You can use use NamespaceIfScoped to override the namespace at the request level.