|
| 1 | +package workspacehelper |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + |
| 7 | + "github.com/hashicorp/terraform-k8s/api/v1alpha1" |
| 8 | + corev1 "k8s.io/api/core/v1" |
| 9 | + "k8s.io/apimachinery/pkg/types" |
| 10 | +) |
| 11 | + |
| 12 | +// GetSecretData retrieves the data from a secret in a given namespace |
| 13 | +func (r *WorkspaceHelper) GetSecretData(namespace string, name string) (map[string][]byte, error) { |
| 14 | + r.reqLogger.Info("Getting Secret", "Namespace", namespace, "Name", name) |
| 15 | + |
| 16 | + secret := &corev1.Secret{} |
| 17 | + err := r.client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, secret) |
| 18 | + if err != nil { |
| 19 | + r.reqLogger.Error(err, "Failed to get Secret", "Namespace", namespace, "Name", name) |
| 20 | + return nil, err |
| 21 | + } |
| 22 | + return secret.Data, nil |
| 23 | +} |
| 24 | + |
| 25 | +// GetSecretForVariable retrieves the sensitive value associated with the variable from a secret |
| 26 | +func (r *WorkspaceHelper) GetSecretForVariable(namespace string, variable *v1alpha1.Variable) error { |
| 27 | + if variable.Sensitive == false || variable.ValueFrom == nil { |
| 28 | + return nil |
| 29 | + } |
| 30 | + |
| 31 | + if variable.ValueFrom.SecretKeyRef == nil { |
| 32 | + err := errors.New("Include Secret in ValueFrom") |
| 33 | + r.reqLogger.Error(err, "No Secret specified", "Namespace", namespace, "Variable", variable.Key) |
| 34 | + return err |
| 35 | + } |
| 36 | + |
| 37 | + r.reqLogger.Info("Checking Secret for variable", "Namespace", namespace, "Variable", variable.Key) |
| 38 | + |
| 39 | + name := variable.ValueFrom.SecretKeyRef.LocalObjectReference.Name |
| 40 | + key := variable.ValueFrom.SecretKeyRef.Key |
| 41 | + |
| 42 | + data, err := r.GetSecretData(namespace, name) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + |
| 47 | + value, ok := data[key] |
| 48 | + if !ok { |
| 49 | + err := errors.New("Include Secret key reference in ValueFrom") |
| 50 | + r.reqLogger.Error(err, "No Secret key specified", "Namespace", namespace, "Name", name, "Key", key) |
| 51 | + return err |
| 52 | + } |
| 53 | + |
| 54 | + variable.Value = string(value) |
| 55 | + return nil |
| 56 | +} |
0 commit comments