sigs.k8s.io/cluster-api@v1.7.1/util/secret/secret.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package secret 18 19 import ( 20 "context" 21 "fmt" 22 "strings" 23 24 "github.com/pkg/errors" 25 corev1 "k8s.io/api/core/v1" 26 "sigs.k8s.io/controller-runtime/pkg/client" 27 ) 28 29 // Get retrieves the specified Secret (if any) from the given 30 // cluster name and namespace. 31 func Get(ctx context.Context, c client.Reader, cluster client.ObjectKey, purpose Purpose) (*corev1.Secret, error) { 32 return GetFromNamespacedName(ctx, c, cluster, purpose) 33 } 34 35 // GetFromNamespacedName retrieves the specified Secret (if any) from the given 36 // cluster name and namespace. 37 func GetFromNamespacedName(ctx context.Context, c client.Reader, clusterName client.ObjectKey, purpose Purpose) (*corev1.Secret, error) { 38 secret := &corev1.Secret{} 39 secretKey := client.ObjectKey{ 40 Namespace: clusterName.Namespace, 41 Name: Name(clusterName.Name, purpose), 42 } 43 44 if err := c.Get(ctx, secretKey, secret); err != nil { 45 return nil, err 46 } 47 48 return secret, nil 49 } 50 51 // Name returns the name of the secret for a cluster. 52 func Name(cluster string, suffix Purpose) string { 53 return fmt.Sprintf("%s-%s", cluster, suffix) 54 } 55 56 // ParseSecretName return the cluster name and the suffix Purpose in name is a valid cluster secret, 57 // otherwise it return error. 58 func ParseSecretName(name string) (string, Purpose, error) { 59 separatorPos := strings.LastIndex(name, "-") 60 if separatorPos == -1 { 61 return "", "", errors.Errorf("%q is not a valid cluster secret name. The purpose suffix is missing", name) 62 } 63 clusterName := name[:separatorPos] 64 purposeSuffix := Purpose(name[separatorPos+1:]) 65 for _, purpose := range allSecretPurposes { 66 if purpose == purposeSuffix { 67 return clusterName, purposeSuffix, nil 68 } 69 } 70 return "", "", errors.Errorf("%q is not a valid cluster secret name. Invalid purpose suffix", name) 71 }