Add label_selector to hetzner service discovery

Allows to filter the servers when sending the listing request to the API. This feature is only available when using the `role=hcloud`.

See https://docs.hetzner.cloud/#label-selector for details on how to use the label selector.

Signed-off-by: Jonas Lammler <jonas.lammler@hetzner-cloud.de>
This commit is contained in:
Jonas Lammler 2025-04-27 13:09:38 +02:00 committed by jo
parent 7789ef27c8
commit 08982b177f
No known key found for this signature in database
GPG Key ID: B2FEC9B22722B984
3 changed files with 18 additions and 6 deletions

View File

@ -53,14 +53,16 @@ const (
// the Discoverer interface.
type hcloudDiscovery struct {
*refresh.Discovery
client *hcloud.Client
port int
client *hcloud.Client
port int
labelSelector string
}
// newHcloudDiscovery returns a new hcloudDiscovery which periodically refreshes its targets.
func newHcloudDiscovery(conf *SDConfig, _ *slog.Logger) (*hcloudDiscovery, error) {
d := &hcloudDiscovery{
port: conf.Port,
port: conf.Port,
labelSelector: conf.LabelSelector,
}
rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "hetzner_sd")
@ -79,7 +81,10 @@ func newHcloudDiscovery(conf *SDConfig, _ *slog.Logger) (*hcloudDiscovery, error
}
func (d *hcloudDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {
servers, err := d.client.Server.All(ctx)
servers, err := d.client.Server.AllWithOpts(ctx, hcloud.ServerListOpts{ListOpts: hcloud.ListOpts{
PerPage: 50,
LabelSelector: d.labelSelector,
}})
if err != nil {
return nil, err
}

View File

@ -59,8 +59,11 @@ type SDConfig struct {
RefreshInterval model.Duration `yaml:"refresh_interval"`
Port int `yaml:"port"`
Role Role `yaml:"role"`
hcloudEndpoint string // For tests only.
robotEndpoint string // For tests only.
LabelSelector string `yaml:"label_selector,omitempty"`
hcloudEndpoint string // For tests only.
robotEndpoint string // For tests only.
}
// NewDiscovererMetrics implements discovery.Config.

View File

@ -1638,6 +1638,10 @@ role: <string>
# The time after which the servers are refreshed.
[ refresh_interval: <duration> | default = 60s ]
# Label selector used to filter the servers when fetching them from the API. See https://docs.hetzner.cloud/#label-selector for more details.
# Only used when role is hcloud.
[ label_selector: <string> ]
# HTTP client settings, including authentication methods (such as basic auth and
# authorization), proxy configurations, TLS options, custom HTTP headers, etc.
[ <http_config> ]