<p>I am working on a dynamic kubernetes informer to watch over my kubernetes cluster for events and  the discovery of all kubernetes components.</p>
<p>But, When I am trying to access the <code>KUBECONFIG</code> via the <code>InClusterConfig</code> method, I am getting the following error:</p>
<pre><code>// go run main.go
FATA[0000] could not get config                          error=&quot;unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined&quot;
exit status 1
</code></pre>
<p>I found various similar issues related to this on kubernetes repo on github as well as stackoverflow but couldn't find any solution or workaround. [<a href="https://github.com/kubernetes/kubernetes/issues/40973#issuecomment-338020558" rel="nofollow noreferrer">kubernetes issue</a>, <a href="https://github.com/coreos/etcd-operator/issues/731" rel="nofollow noreferrer">kubernetes issue</a>, <a href="https://stackoverflow.com/questions/53394844/in-cluster-config-is-unable-to-get-pods-when-deployed-in-a-non-default-namespace">stackoverflow similar question</a>, <a href="https://stackoverflow.com/questions/55162573/issue-using-in-cluster-kubernetes-configuration-with-client-go-library-on-google">stackoverflow similar question</a>]</p>
<p>Following is the go code and go.mod file</p>
<p><strong>Go Code</strong>:</p>
<pre><code>package main

import (
    &quot;os&quot;
    &quot;os/signal&quot;

    &quot;github.com/sirupsen/logrus&quot;
    v1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;
    &quot;k8s.io/apimachinery/pkg/apis/meta/v1/unstructured&quot;
    &quot;k8s.io/apimachinery/pkg/runtime/schema&quot;
    &quot;k8s.io/client-go/dynamic&quot;
    &quot;k8s.io/client-go/dynamic/dynamicinformer&quot;
    &quot;k8s.io/client-go/rest&quot;
    &quot;k8s.io/client-go/tools/cache&quot;
    &quot;k8s.io/client-go/tools/clientcmd&quot;
)

func main() {
    cfg, err := restConfig()
    if err != nil {
        logrus.WithError(err).Fatal(&quot;could not get config&quot;)
    }

    // Grab a dynamic interface that we can create informers from
    dc, err := dynamic.NewForConfig(cfg)
    if err != nil {
        logrus.WithError(err).Fatal(&quot;could not generate dynamic client for config&quot;)
    }

    // Create a factory object that we can say &quot;hey, I need to watch this resource&quot;
    // and it will give us back an informer for it
    f := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dc, 0, v1.NamespaceAll, nil)

    // Retrieve a &quot;GroupVersionResource&quot; type that we need when generating our informer from our dynamic factory
    gvr, _ := schema.ParseResourceArg(&quot;deployments.v1.apps&quot;)

    // Finally, create our informer for deployments!
    i := f.ForResource(*gvr)

    stopCh := make(chan struct{})
    go startWatching(stopCh, i.Informer())

    sigCh := make(chan os.Signal, 0)
    signal.Notify(sigCh, os.Kill, os.Interrupt)

    &lt;-sigCh
    close(stopCh)
}

func restConfig() (*rest.Config, error) {
    kubeCfg, err := rest.InClusterConfig()
    if kubeconfig := os.Getenv(&quot;KUBECONFIG&quot;); kubeconfig != &quot;&quot; {
        kubeCfg, err = clientcmd.BuildConfigFromFlags(&quot;&quot;, kubeconfig)
    }

    // var kubeCfg *string
    // if home := homedir.HomeDir(); home != &quot;&quot; {
    //  kubeCfg = flag.String(&quot;kubeconfig&quot;, filepath.Join(home, &quot;.kube&quot;, &quot;config&quot;), &quot;(optional) absolute path to the kubeconfig file&quot;)
    // } else {
    //  kubeCfg = flag.String(&quot;kubeconfig&quot;, &quot;&quot;, &quot;absolute path to the kubeconfig file&quot;)
    // }
    // flag.Parse()

    // kubeCfg, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, *kubeconfig)

    //testing-ends

    if err != nil {
        return nil, err
    }

    return kubeCfg, nil
}

func startWatching(stopCh &lt;-chan struct{}, s cache.SharedIndexInformer) {
    handlers := cache.ResourceEventHandlerFuncs{
        AddFunc: func(obj interface{}) {
            u := obj.(*unstructured.Unstructured)

            logrus.WithFields(logrus.Fields{
                &quot;name&quot;:      u.GetName(),
                &quot;namespace&quot;: u.GetNamespace(),
                &quot;labels&quot;:    u.GetLabels(),
            }).Info(&quot;received add event!&quot;)
        },
        UpdateFunc: func(oldObj, obj interface{}) {
            logrus.Info(&quot;received update event!&quot;)
        },
        DeleteFunc: func(obj interface{}) {
            logrus.Info(&quot;received update event!&quot;)
        },
    }

    s.AddEventHandler(handlers)
    s.Run(stopCh)
}
</code></pre>
<p><strong>go.mod file</strong>:</p>
<pre><code>module discovery-test

go 1.15

require (
    github.com/googleapis/gnostic v0.5.3 // indirect
    github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect
    github.com/imdario/mergo v0.3.11 // indirect
    github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
    github.com/sirupsen/logrus v1.7.0
    golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 // indirect
    golang.org/x/net v0.0.0-20201029055024-942e2f445f3c // indirect
    golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 // indirect
    golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirect
    k8s.io/apimachinery v0.17.0
    k8s.io/client-go v0.17.0
    k8s.io/klog v1.0.0 // indirect
    k8s.io/utils v0.0.0-20201027101359-01387209bb0d // indirect
)
</code></pre>

<p>First of all, thanks to @ShudiptaSharma. His comment helped me in figuring out that I was trying to get the cluster config from outside of the cluster which was leading the program on my local machine (127.0.0.1) from where I am not able to access the cluster.</p>
<p>Further, I tried to figure out how to access the cluster from outside the cluster and found that <code>InClusterConfig</code> is used for running inside cluster use case, when running outside the cluster, something like the following can be used:</p>
<pre><code>//go run main.go
package main

import (
    &quot;os&quot;
    &quot;os/signal&quot;
  //&quot;context&quot;
    &quot;flag&quot;
    //&quot;fmt&quot;
    &quot;path/filepath&quot;
    //&quot;time&quot;

    &quot;github.com/sirupsen/logrus&quot;
    v1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;
    &quot;k8s.io/apimachinery/pkg/apis/meta/v1/unstructured&quot;
    &quot;k8s.io/apimachinery/pkg/runtime/schema&quot;
    &quot;k8s.io/client-go/dynamic&quot;
    &quot;k8s.io/client-go/dynamic/dynamicinformer&quot;
    //&quot;k8s.io/client-go/rest&quot;
    &quot;k8s.io/client-go/tools/cache&quot;
    &quot;k8s.io/client-go/tools/clientcmd&quot;
  &quot;k8s.io/client-go/util/homedir&quot;
)

func main() {
  //kubeconfig := os.Getenv(&quot;KUBECONFIG&quot;)
  
  var kubeconfig *string
    if home := homedir.HomeDir(); home != &quot;&quot; {
        kubeconfig = flag.String(&quot;kubeconfig&quot;, filepath.Join(home, &quot;.kube&quot;, &quot;config&quot;), &quot;(optional) absolute path to the kubeconfig file&quot;)
    } else {
        kubeconfig = flag.String(&quot;kubeconfig&quot;, &quot;&quot;, &quot;absolute path to the kubeconfig file&quot;)
    }
    flag.Parse()
  
    cfg, err := clientcmd.BuildConfigFromFlags(&quot;&quot;, *kubeconfig)
    if err != nil {
        logrus.WithError(err).Fatal(&quot;could not get config&quot;)
    }

    // Grab a dynamic interface that we can create informers from
    dc, err := dynamic.NewForConfig(cfg)
    if err != nil {
        logrus.WithError(err).Fatal(&quot;could not generate dynamic client for config&quot;)
    }

    // Create a factory object that we can say &quot;hey, I need to watch this resource&quot;
    // and it will give us back an informer for it
    f := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dc, 0, v1.NamespaceAll, nil)

    // Retrieve a &quot;GroupVersionResource&quot; type that we need when generating our informer from our dynamic factory
    gvr, _ := schema.ParseResourceArg(&quot;deployments.v1.apps&quot;)

    // Finally, create our informer for deployments!
    i := f.ForResource(*gvr)

    stopCh := make(chan struct{})
    go startWatching(stopCh, i.Informer())

    sigCh := make(chan os.Signal, 0)
    signal.Notify(sigCh, os.Kill, os.Interrupt)

    &lt;-sigCh
    close(stopCh)
}

func startWatching(stopCh &lt;-chan struct{}, s cache.SharedIndexInformer) {
    handlers := cache.ResourceEventHandlerFuncs{
        AddFunc: func(obj interface{}) {
            u := obj.(*unstructured.Unstructured)

            logrus.WithFields(logrus.Fields{
                &quot;name&quot;:      u.GetName(),
                &quot;namespace&quot;: u.GetNamespace(),
                &quot;labels&quot;:    u.GetLabels(),
            }).Info(&quot;received add event!&quot;)
        },
        UpdateFunc: func(oldObj, obj interface{}) {
            logrus.Info(&quot;received update event!&quot;)
        },
        DeleteFunc: func(obj interface{}) {
            logrus.Info(&quot;received update event!&quot;)
        },
    }

    s.AddEventHandler(handlers)
    s.Run(stopCh)
}
</code></pre>
