aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAleksandr Nogikh <nogikh@google.com>2025-05-08 12:36:37 +0200
committerTaras Madan <tarasmadan@google.com>2025-05-09 08:56:10 +0000
commit8ea579ebca8bcbeb1325837666a3093e86d45fa4 (patch)
tree6734fe3bc31ef2c3c2b4b5ba4118cd3c685042ea
parent6f914b33a42faaa48f4d49115e69fb8bfd0e58eb (diff)
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.
-rw-r--r--pkg/gce/gcp_secret.go25
1 files changed, 24 insertions, 1 deletions
diff --git a/pkg/gce/gcp_secret.go b/pkg/gce/gcp_secret.go
index f9b607bf4..ef4eb2341 100644
--- a/pkg/gce/gcp_secret.go
+++ b/pkg/gce/gcp_secret.go
@@ -5,18 +5,23 @@ package gce
import (
"context"
+ "fmt"
+ "cloud.google.com/go/compute/metadata"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)
// GcpSecret returns the GCP Secret Manager blob as a []byte data.
func GcpSecret(name string) ([]byte, error) {
+ return GcpSecretWithContext(context.Background(), name)
+}
+
+func GcpSecretWithContext(ctx context.Context, name string) ([]byte, error) {
// name := "projects/my-project/secrets/my-secret/versions/5"
// name := "projects/my-project/secrets/my-secret/versions/latest"
// Create the client.
- ctx := context.Background()
client, err := secretmanager.NewClient(ctx)
if err != nil {
return nil, err
@@ -36,3 +41,21 @@ func GcpSecret(name string) ([]byte, error) {
return result.Payload.Data, nil
}
+
+// LatestGcpSecret returns the latest secret value.
+func LatestGcpSecret(ctx context.Context, projectName, key string) ([]byte, error) {
+ return GcpSecretWithContext(ctx,
+ fmt.Sprintf("projects/%s/secrets/%s/versions/latest", projectName, key))
+}
+
+// ProjectName returns the name of the GCP project the code is running on.
+func ProjectName(ctx context.Context) (string, error) {
+ if !metadata.OnGCE() {
+ return "", fmt.Errorf("not running on GKE/GCE")
+ }
+ projectID, err := metadata.ProjectIDWithContext(ctx)
+ if err != nil {
+ return "", err
+ }
+ return projectID, nil
+}