forked from gitops-tools/pkg
/
secrets.go
37 lines (32 loc) · 1014 Bytes
/
secrets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package secrets
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// KubeSecretGetter is an implementation of SecretGetter.
type KubeSecretGetter struct {
kubeClient client.Client
}
// New creates and returns a KubeSecretGetter that looks up secrets in k8s.
func New(c client.Client) *KubeSecretGetter {
return &KubeSecretGetter{
kubeClient: c,
}
}
// SecretToken looks for a namespaced secret, and returns the key from
// it, or an error if not found.
func (k KubeSecretGetter) SecretToken(ctx context.Context, id types.NamespacedName, key string) (string, error) {
loaded := &corev1.Secret{}
err := k.kubeClient.Get(context.TODO(), id, loaded)
if err != nil {
return "", fmt.Errorf("error getting secret %s/%s: %w", id.Namespace, id.Name, err)
}
token, ok := loaded.Data[key]
if !ok {
return "", fmt.Errorf("secret invalid, no %#v key in %s/%s", key, id.Namespace, id.Name)
}
return string(token), nil
}