@@ -29,6 +29,7 @@ import (
2929 flag "github.com/spf13/pflag"
3030 "go.uber.org/zap/zapcore"
3131 apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation"
32+ "k8s.io/apimachinery/pkg/labels"
3233 "k8s.io/apimachinery/pkg/runtime/schema"
3334 "k8s.io/klog/v2"
3435 ctrlrt "sigs.k8s.io/controller-runtime"
@@ -54,6 +55,7 @@ const (
5455 flagLogLevel = "log-level"
5556 flagResourceTags = "resource-tags"
5657 flagWatchNamespace = "watch-namespace"
58+ flagWatchSelectors = "watch-selectors"
5759 flagEnableWebhookServer = "enable-webhook-server"
5860 flagWebhookServerAddr = "webhook-server-addr"
5961 flagDeletionPolicy = "deletion-policy"
@@ -94,6 +96,7 @@ type Config struct {
9496 LogLevel string
9597 ResourceTags []string
9698 WatchNamespace string
99+ WatchSelectors string
97100 EnableWebhookServer bool
98101 WebhookServerAddr string
99102 DeletionPolicy ackv1alpha1.DeletionPolicy
@@ -202,6 +205,14 @@ func (cfg *Config) BindFlags() {
202205 "A comma-separated list of valid RFC-1123 namespace names to watch for custom resource events. " +
203206 "If unspecified, the controller watches for events in all namespaces." ,
204207 )
208+ flag .StringVar (
209+ & cfg .WatchSelectors , flagWatchSelectors ,
210+ "" ,
211+ "A comma-separated list of valid label (object) selectors to filter the objects." +
212+ " For example, you can use the label selectors similar to 'app=foo,env=sbx' " +
213+ " to only watch objects that have the 'app' label set to 'foo' and the 'env' label set to 'sbx'. " +
214+ " If unspecified, the controller will not filter the objects." ,
215+ )
205216 flag .Var (
206217 & cfg .DeletionPolicy , flagDeletionPolicy ,
207218 "The default deletion policy for all resources managed by the controller" ,
@@ -457,6 +468,25 @@ func parseReconcileFlagArgument(flagArgument string) (string, int, error) {
457468 return elements [0 ], value , nil
458469}
459470
471+ // ParseWatchSelectors parses the --watch-selectors flag and returns a label selector
472+ // that can be used to filter the objects that the controller watches. If the flag is
473+ // not set, the function returns nil, which means that the controller will watch all
474+ // objects.
475+ func (cfg * Config ) ParseWatchSelectors () (labels.Selector , error ) {
476+ // If the WatchSelectors isn't set, return nil. controller-runtime will be in charge
477+ // of defaulting to watching all objects.
478+ if cfg .WatchSelectors == "" {
479+ return nil , nil
480+ }
481+
482+ labelSelector , err := labels .Parse (cfg .WatchSelectors )
483+ if err != nil {
484+ return nil , fmt .Errorf ("invalid value for flag '%s': %v" , flagWatchSelectors , err )
485+ }
486+
487+ return labelSelector , nil
488+ }
489+
460490// GetWatchNamespaces returns a slice of namespaces to watch for custom resource events.
461491// If the watchNamespace flag is empty, the function returns nil, which means that the
462492// controller will watch for events in all namespaces.
0 commit comments