Skip to content

Commit

Permalink
Add basic auth for Prometheus client
Browse files Browse the repository at this point in the history
  • Loading branch information
jrauh01 committed Aug 21, 2024
1 parent 77cf19e commit 824fa2a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
17 changes: 15 additions & 2 deletions cmd/icinga-kubernetes/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"k8s.io/client-go/kubernetes"
kclientcmd "k8s.io/client-go/tools/clientcmd"
"k8s.io/klog/v2"
"net/http"
"os"
"strings"
"time"
Expand Down Expand Up @@ -128,9 +129,21 @@ func main() {
}

if cfg.Prometheus.Url != "" {
promClient, err := promapi.NewClient(promapi.Config{Address: cfg.Prometheus.Url})
var basicAuthTransport http.RoundTripper

if cfg.Prometheus.Username != "" && cfg.Prometheus.Password != "" {
basicAuthTransport = &internal.BasicAuthTransport{
Username: cfg.Prometheus.Username,
Password: cfg.Prometheus.Password,
}
}

promClient, err := promapi.NewClient(promapi.Config{
Address: cfg.Prometheus.Url,
RoundTripper: basicAuthTransport,
})
if err != nil {
klog.Fatal(errors.Wrap(err, "error creating promClient"))
klog.Fatal(errors.Wrap(err, "error creating Prometheus client"))
}

promApiClient := promv1.NewAPI(promClient)
Expand Down
20 changes: 20 additions & 0 deletions internal/basic_auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package internal

import (
"encoding/base64"
"net/http"
)

// BasicAuthTransport is a http.RoundTripper that authenticates all requests using HTTP Basic Authentication
type BasicAuthTransport struct {
Username string
Password string
}

// RoundTrip executes a single HTTP transaction with the basic auth credentials
func (rt *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(rt.Username+":"+rt.Password))
req.Header.Set("Authorization", basicAuth)

return http.DefaultTransport.RoundTrip(req)
}
4 changes: 3 additions & 1 deletion pkg/metrics/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (

// PrometheusConfig defines Prometheus configuration.
type PrometheusConfig struct {
Url string `yaml:"url"`
Url string `yaml:"url"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}

// Validate checks constraints in the supplied Prometheus configuration and returns an error if they are violated.
Expand Down

0 comments on commit 824fa2a

Please sign in to comment.