Home > Back-end >  How to apply top level namespace using kubernetes go client
How to apply top level namespace using kubernetes go client

Time:07-15

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.

CodePudding user response:

Most functions for creating resources in the Kubernetes go client accept the namespace for an argument.

You can also set a different default namespace in your kubeconfig context:

contexts:
- context:
    cluster: example
    namespace: mynamespace
    user: example
  name: example

More details can be found here:

https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/

Then when you import your kubeconfig, all your resources should be created in that namespace. Look at this example on how to import your kubeconfig:

main.go

CodePudding user response:

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.

  • Related