List deployments using apimachinery by the .spec.selector.matchLabels key

11/9/2021

I want to list my deployments based on a key value pair found in the .spec.selector.matchLabels field.

Doing so using the plain labels is easy, but I could not find a way to match / fetch the deployment that satisfies the condition that a certain key=value is present in the following section

spec:
  [...]
  selector:
    matchLabels:
      app: myapp
      process: web
      release: myrelease

Does not seem this can be done using the ListOptions

-- pkaramol
client-go
go
kubernetes

1 Answer

11/22/2021

It is not supported:

You have to filter on the client side:

	depl, err := clientset.AppsV1().Deployments("some_namespace").List(context.Background(), metav1.ListOptions{})
	if err != nil {
		panic(err.Error())
	}
	for _, item := range depl.Items {
		if item.Spec.Selector.MatchLabels["app"] == "myapp" {
			fmt.Println("found it")
		}
	}
-- blackgreen
Source: StackOverflow