3

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
  • 12,992
  • 9
  • 53
  • 89

3 Answers3

2

as mentioned above, secret object resides in a namespace. They can only be referenced by pods in that same namespace.

Sharing secret across namespaces

if you want to use the secret in multiple namespaces, copy the same secret into the desired namespaces.

example case

  • kubernetes secret: test-secret-1
  • namespace from: testns1
  • namespace to: testns2
  1. Using pipe "|" operator
kubectl get secret test-secret-1 --namespace=testns1 -oyaml | grep -v ^\s*namespace:\s' |kubectl apply --namespace=testns2 -f -
  1. Using sed command
kubectl get secret test-secret-1 -n testns1 -o yaml | sed s/"namespace: testns1"/"namespace: testns2"/| kubectl 
apply -n testns2 -f -
  1. Export kubernetes secret to yaml and apply secret
kubectl get secret test-secret-1 -n testns1 -o yaml
apiVersion: v1
data:
  password: dGVzdFBAc3N3b3Jk
  username: dGVzdC11c2Vy
kind: Secret
metadata:
  creationTimestamp: "2021-11-11T21:21:02Z"
  name: test-secret-1
  namespace: testns1 # change namespace to testns2
  resourceVersion: "307939"
  uid: 6a8d9a6d-9648-4a39-a362-150e682c9a42
type: Opaque

https://jhooq.com/kubernetes-share-secrets-namespaces/

KRyun
  • 23
  • 1
  • 6
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](https://meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted](https://stackoverflow.com/help/deleted-answers). – Tyler2P Jul 30 '22 at 08:18
  • thanks to notice me, I've edited the answer with code. – KRyun Aug 01 '22 at 01:10
1

You can't read a secret from a different namespace from where you are making the request.

  • 1
    can you clarify what you mean? – The Fool Jul 26 '22 at 18:39
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 01 '22 at 15:10
0

Via "k8s.io/client-go/kubernetes" you can get the secret, full example in https://github.com/minio/operator/blob/master/pkg/controller/cluster/main-controller.go something similar to:

import (
    "k8s.io/client-go/kubernetes"
)

...

type Controller struct {

    // kubeClientSet is a standard kubernetes clientset
    kubeClientSet kubernetes.Interface
}

...

// Trying to get just the csr-signer secret not the entire list from openshift-kube-controller-manager-operator namespace
secret, _ := c.kubeClientSet.CoreV1().Secrets("openshift-kube-controller-manager-operator").Get(
    ctx, "csr-signer", metav1.GetOptions{})
Cesar Celis
  • 166
  • 1
  • 4
  • 8