-
Notifications
You must be signed in to change notification settings - Fork 444
/
secret.go
63 lines (51 loc) · 1.8 KB
/
secret.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package kube
import (
"context"
errors "github.com/rotisserie/eris"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"github.com/solo-io/go-utils/contextutils"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
type TlsSecret struct {
SecretName, SecretNamespace string
PrivateKeyFileName, CertFileName, CaBundleFileName string
PrivateKey, Cert, CaBundle []byte
}
func CreateTlsSecret(ctx context.Context, kube kubernetes.Interface, secretCfg TlsSecret) error {
secret := makeTlsSecret(secretCfg)
secretClient := kube.CoreV1().Secrets(secret.Namespace)
contextutils.LoggerFrom(ctx).Infow("creating TLS secret", zap.String("secret", secret.Name))
if _, err := secretClient.Create(secret); err != nil {
if apierrors.IsAlreadyExists(err) {
contextutils.LoggerFrom(ctx).Infow("existing TLS secret found, attempting to update", zap.String("secret", secret.Name))
existing, err := secretClient.Get(secret.Name, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to retrieve existing secret after receiving AlreadyExists error on Create")
}
secret.ResourceVersion = existing.ResourceVersion
if _, err := secretClient.Update(secret); err != nil {
return errors.Wrapf(err, "failed updating existing secret")
}
return nil
}
return errors.Wrapf(err, "failed creating secret")
}
return nil
}
func makeTlsSecret(args TlsSecret) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: args.SecretName,
Namespace: args.SecretNamespace,
},
Type: v1.SecretTypeTLS,
Data: map[string][]byte{
args.PrivateKeyFileName: args.PrivateKey,
args.CertFileName: args.Cert,
args.CaBundleFileName: args.CaBundle,
},
}
}