|
| 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 remote |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/base64" |
| 22 | + "fmt" |
| 23 | + |
| 24 | + "github.com/pkg/errors" |
| 25 | + corev1 "k8s.io/api/core/v1" |
| 26 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 27 | +) |
| 28 | + |
| 29 | +const ( |
| 30 | + kubeconfigSecretKey = "value" |
| 31 | +) |
| 32 | + |
| 33 | +// KubeConfigSecretName generates the expected name for the Kubeconfig secret |
| 34 | +// to access a remote cluster given the cluster's name. |
| 35 | +func KubeConfigSecretName(cluster string) string { |
| 36 | + return fmt.Sprintf("%s-kubeconfig", cluster) |
| 37 | +} |
| 38 | + |
| 39 | +// GetKubeConfigSecret retrieves the KubeConfig Secret (if any) |
| 40 | +// from the given cluster name and namespace. |
| 41 | +func GetKubeConfigSecret(c client.Client, cluster, namespace string) (*corev1.Secret, error) { |
| 42 | + secret := &corev1.Secret{} |
| 43 | + secretKey := client.ObjectKey{ |
| 44 | + Namespace: namespace, |
| 45 | + Name: KubeConfigSecretName(cluster), |
| 46 | + } |
| 47 | + |
| 48 | + if err := c.Get(context.TODO(), secretKey, secret); err != nil { |
| 49 | + return nil, err |
| 50 | + } |
| 51 | + |
| 52 | + return secret, nil |
| 53 | +} |
| 54 | + |
| 55 | +// DecodeKubeConfigSecret uses the Secret to retrieve and decode the data. |
| 56 | +func DecodeKubeConfigSecret(secret *corev1.Secret) ([]byte, error) { |
| 57 | + encodedKubeconfig, ok := secret.Data[kubeconfigSecretKey] |
| 58 | + if !ok { |
| 59 | + return nil, errors.Errorf("missing value in secret %s/%s", secret.Namespace, secret.Name) |
| 60 | + } |
| 61 | + |
| 62 | + kubeconfig, err := base64.StdEncoding.DecodeString(string(encodedKubeconfig)) |
| 63 | + if err != nil { |
| 64 | + return nil, errors.Wrapf(err, "cannot decode kubeconfig secret %s/%s", secret.Namespace, secret.Name) |
| 65 | + } |
| 66 | + |
| 67 | + return kubeconfig, nil |
| 68 | +} |
0 commit comments