Skip to content

Commit

Permalink
fix: Use TokenRequest API to get prometheus token
Browse files Browse the repository at this point in the history
Getting the token using TokenRequest API is more stable
than listing all secrets and looking for the right one.

Signed-off-by: Andrej Krejcir <[email protected]>
  • Loading branch information
akrejcir committed Jan 26, 2024
1 parent 14f49ea commit e2fd184
Showing 1 changed file with 7 additions and 25 deletions.
32 changes: 7 additions & 25 deletions tests/monitoring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ package tests
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"

. "github.com/onsi/ginkgo/v2"
Expand All @@ -19,6 +17,7 @@ import (
promApiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
promConfig "github.com/prometheus/common/config"
apps "k8s.io/api/apps/v1"
authnv1 "k8s.io/api/authentication/v1"
core "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
Expand Down Expand Up @@ -410,28 +409,11 @@ func getPrometheusUrl() string {
}

func getAuthorizationTokenForPrometheus() string {
var token string
Eventually(func() error {
secretList := &core.SecretList{}
namespace := client.InNamespace(metrics.MonitorNamespace)
err := apiClient.List(ctx, secretList, namespace)
if err != nil {
return fmt.Errorf("error getting secret: %w", err)
}
var tokenBytes []byte
var ok bool
for _, secret := range secretList.Items {
if strings.HasPrefix(secret.Name, "prometheus-k8s-token") {
tokenBytes, ok = secret.Data["token"]
if !ok {
return errors.New("token not found in secret data")
}
break
}
}
const serviceAccountName = "prometheus-k8s"
tokenReview, err := coreClient.CoreV1().ServiceAccounts(metrics.MonitorNamespace).
CreateToken(ctx, serviceAccountName, &authnv1.TokenRequest{}, metav1.CreateOptions{})

Expect(err).ToNot(HaveOccurred())

token = string(tokenBytes)
return nil
}, 10*time.Second, time.Second).Should(Succeed())
return token
return tokenReview.Status.Token
}

0 comments on commit e2fd184

Please sign in to comment.