@@ -5,18 +5,23 @@ package gce
55
66import (
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.
1416func 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