LabelSelector for Secrets List in k8s
12,762
Solution 1
You can use the k8s provided function to do the toString operation
import "k8s.io/apimachinery/pkg/labels"
...
func GetSecret(version string) (retVal interface{}, err error){
clientset := GetClientOutOfCluster()
labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}
listOptions := metav1.ListOptions{
LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
Limit: 100,
}
secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
retVal = secretList.Items[0]
return retVal, err
}
Solution 2
func GetSecret( version string, param2 string) (retVal interface{}, err error){
clientset := GetClientOutOfCluster()
labelSelector := fmt.Sprintf("version=%s, param2=%s", version, param2)
listOptions := metav1.ListOptions{
LabelSelector: labelSelector,
Limit: 100,
}
secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
retVal = secretList.Items[0]
return retVal, err
}
Related videos on Youtube
Author by
AlexS
Updated on June 04, 2022Comments
-
AlexS almost 2 years
I want to get Secret object from k8s cluster using go-client API
I have function that looks like that
func GetSecret( version string) (retVal interface{}, err error){ clientset := GetClientOutOfCluster() labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}} listOptions := metav1.ListOptions{ LabelSelector: labelSelector.String(), Limit: 100, } secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions ) retVal = secretList.Items[0] return retVal, err }
GetClientOutOfCluster is basically retrieves configuration from cluster or from local ~/.kube/config
I used metav1.LabelSelector just like i do when i generate new Deployment object.So i thought i was cool. But ListOptions.LabelSelector is a string. When i run my function it fails.
unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{version:": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')
I cannot find example of usage of this function anywhere. Documentation assumes that you know what is LabelSelector.
What is format of LabelSelector for ListOptions?
Thanks
-
mdaniel almost 6 yearsI would assume it's the same syntax as
kubectl
's--selector
argument:some-key=some-value,other-key=something-else
; have you already tried that? In your specific case, I would think:labelSelector: fmt.Sprintf("version=%s", version),
-
-
Daniel Schütte almost 6 yearsPlease try to make this a complete answer to help others who read the question to understand your solution.