-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret.go
66 lines (58 loc) · 1.94 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
64
65
66
package gcp
import (
"context"
"fmt"
"strings"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)
type Secret *secretmanagerpb.Secret
// FetchSecret will fetch a secret by name for a given project
func FetchSecret(ctx context.Context, projectID string, name string) ([]byte, error) {
client, err := secretmanager.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to setup secret client: %w", err)
}
defer client.Close()
accessRequest := &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/latest", projectID, name),
}
result, err := client.AccessSecretVersion(ctx, accessRequest)
if err != nil {
return nil, fmt.Errorf("failed to access secret %s version: %w", name, err)
}
return result.Payload.Data, nil
}
func WriteSecret(ctx context.Context, projectID string, name string, sercretValue []byte) error {
client, err := secretmanager.NewClient(ctx)
if err != nil {
return fmt.Errorf("failed to setup secret client: %w", err)
}
defer client.Close()
createRequest := &secretmanagerpb.CreateSecretRequest{
Parent: fmt.Sprintf("projects/%s", projectID),
SecretId: name,
Secret: &secretmanagerpb.Secret{
Replication: &secretmanagerpb.Replication{
Replication: &secretmanagerpb.Replication_Automatic_{
Automatic: &secretmanagerpb.Replication_Automatic{},
},
},
},
}
_, err = client.CreateSecret(ctx, createRequest)
if err != nil && !strings.Contains(err.Error(), "AlreadyExists") {
return fmt.Errorf("failed to create secret: %w", err)
}
addVersionRequest := &secretmanagerpb.AddSecretVersionRequest{
Parent: fmt.Sprintf("projects/%s/secrets/%s", projectID, name),
Payload: &secretmanagerpb.SecretPayload{
Data: sercretValue,
},
}
_, err = client.AddSecretVersion(ctx, addVersionRequest)
if err != nil {
return fmt.Errorf("failed to create secret version: %w", err)
}
return nil
}