Get a secret with k8s.io library

1/29/2022

I am totally new to Go and the Kubernetes library k8s.io (https://github.com/kubernetes/client-go) and try to figure out how to get a specific secret.

I have a kind of observer which watches changes of Secrets. I am iterating through a Secretlist within a specific namespace. That works, I also can filter them by a while loop. But I do not know how to get and search a Secret in a different namespace which should be available in this loop.

I need a secret named XXX in namespace "my-namespace" (I know that the following line does not exist, it should only outline the idea what I am looking for) I come from Ruby, so I searched for something like this :

var myKubeSecret = kubernetes.V1().Secrets("my-namespace").Find("XXX")

Exists like the function like that one above?

This is what I have: this observes all my secrets in namespace "default". Which works. That example was taken from a Code that does something similar I was searching for, and I try to modify now.:

import (

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	kubeinformers "k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"sigs.k8s.io/yaml"
)
// a lot of code
// ....
// ...
// ..
// .

if data, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil {
		fmt.Println("data",data)
	}
	// listen for new secrets
	factory := kubeinformers.NewSharedInformerFactoryWithOptions(clientsetCore, 0, kubeinformers.WithNamespace(namespace()))
	informer := factory.Core().V1().Secrets().Informer()
	secrets := factory.Core().V1().Secrets().Lister()

var myKubeSecret string // will hold my secret

informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  AddFunc: func(new interface{}) {
    // get the secret
    var cpSecret = new.(*v1.Secret).DeepCopy()
     	if mySecret.GetName() == "argocd-credentials" {
				var cpData = *&cpSecret.Data
				for k, v := range cpData {
					clusterIP = kubeConfig.Clusters[0].Cluster.Server

					fmt.Println("cpData k:", k, "v:", v)
					switch k {
					case "authToken":
						fmt.Println("authToken:", v)

                    // ### HERE SHOULD BE THE VALUE OF A
                    // ### SECRET NAMED XXX in ns my-namespace 
                    myKubeSecret = // ### should a bearerToken string
					}
				}
			}
      }
}

I hope you get the idea..

Please also tell me which import libray is needed, if any.

-- Jan
go
kubernetes
kubernetes-go-client

0 Answers