Skip to content

Commit f958dc9

Browse files
committed
pkg/gcs: add helper methods for secret retrieval
Add a method for querying the current project name. Add a method for querying the latest secret version.
1 parent a2abf23 commit f958dc9

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

pkg/gce/gcp_secret.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,23 @@ package gce
55

66
import (
77
"context"
8+
"fmt"
89

10+
"cloud.google.com/go/compute/metadata"
911
secretmanager "cloud.google.com/go/secretmanager/apiv1"
1012
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
1113
)
1214

1315
// GcpSecret returns the GCP Secret Manager blob as a []byte data.
1416
func GcpSecret(name string) ([]byte, error) {
17+
return GcpSecretWithContext(context.Background(), name)
18+
}
19+
20+
func GcpSecretWithContext(ctx context.Context, name string) ([]byte, error) {
1521
// name := "projects/my-project/secrets/my-secret/versions/5"
1622
// name := "projects/my-project/secrets/my-secret/versions/latest"
1723

1824
// Create the client.
19-
ctx := context.Background()
2025
client, err := secretmanager.NewClient(ctx)
2126
if err != nil {
2227
return nil, err
@@ -36,3 +41,21 @@ func GcpSecret(name string) ([]byte, error) {
3641

3742
return result.Payload.Data, nil
3843
}
44+
45+
// LatestGcpSecret returns the latest secret value.
46+
func LatestGcpSecret(ctx context.Context, projectName, key string) ([]byte, error) {
47+
return GcpSecretWithContext(ctx,
48+
fmt.Sprintf("projects/%s/secrets/%s/versions/latest", projectName, key))
49+
}
50+
51+
// ProjectName returns the name of the GCP project the code is running on.
52+
func ProjectName(ctx context.Context) (string, error) {
53+
if !metadata.OnGCE() {
54+
return "", fmt.Errorf("not running on GKE/GCE")
55+
}
56+
projectID, err := metadata.ProjectIDWithContext(ctx)
57+
if err != nil {
58+
return "", err
59+
}
60+
return projectID, nil
61+
}

0 commit comments

Comments
 (0)