-
Notifications
You must be signed in to change notification settings - Fork 50
/
client.go
56 lines (46 loc) · 1.51 KB
/
client.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
package gcs
import (
"context"
"fmt"
"github.com/googleapis/google-cloud-go-testing/storage/stiface"
"github.com/openshift/managed-velero-operator/config"
"github.com/openshift/managed-velero-operator/version"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
gstorage "cloud.google.com/go/storage"
goauth2 "golang.org/x/oauth2/google"
goption "google.golang.org/api/option"
)
var (
storageCredsSecretName = version.OperatorName + "-iam-credentials"
)
// NewGcsClient reads the gcp secrets in the operator's namespace and uses
// them to create a new client for accessing the GCS API.
func NewGcsClient(kubeClient client.Client) (stiface.Client, error) {
var err error
namespace := config.OperatorNamespace
secret := &corev1.Secret{}
err = kubeClient.Get(context.TODO(),
types.NamespacedName{
Name: storageCredsSecretName,
Namespace: namespace,
},
secret)
if err != nil {
return nil, err
}
keyFileData, ok := secret.Data["service_account.json"]
if !ok {
return nil, fmt.Errorf("secret %q does not contain required key \"service_account.json\"", fmt.Sprintf("%s/%s", namespace, storageCredsSecretName))
}
credentials, err := goauth2.CredentialsFromJSON(context.TODO(), []byte(string(keyFileData)), gstorage.ScopeFullControl)
if err != nil {
return nil, err
}
gcsClient, err := gstorage.NewClient(context.TODO(), goption.WithCredentials(credentials))
if err != nil {
return nil, err
}
return stiface.AdaptClient(gcsClient), nil
}