Retrieves Multiple Variable in Gcp Secret Manager With Json Format
To create a Google Cloud Function in Go that retrieves variables from Google Cloud Secret Manager in JSON format, you’ll need to use the Google Cloud Functions SDK and the Secret Manager client libraries. Here’s a step-by-step guide on how to do it:
-
Set up your development environment:
- Make sure you have the Go programming language installed on your machine.
- Install the Google Cloud SDK and set up your Google Cloud project.
- Authenticate your Google Cloud SDK using
gcloud auth login
.
-
Create a new Go module for your Cloud Function:
mkdir my-cloud-function cd my-cloud-function go mod init my-cloud-function
-
Install the necessary Go packages:
go get cloud.google.com/go/functions go get cloud.google.com/go/secretmanager
-
Create your Go Cloud Function in a file named
main.go
:package main import ( "context" "encoding/json" "fmt" "net/http" "cloud.google.com/go/functions/metadata" "cloud.google.com/go/secretmanager" ) type SecretData struct { // Define the structure of your secret JSON here Variable1 string `json:"variable1"` Variable2 string `json:"variable2"` // Add more fields as needed } func retrieveSecretData(ctx context.Context, w http.ResponseWriter, r *http.Request) error { // Extract the function metadata meta, err := metadata.FromContext(ctx) if err != nil { return err } // Specify your secret name secretName := "projects/YOUR_PROJECT_ID/secrets/YOUR_SECRET_NAME/versions/latest" // Create a Secret Manager client client, err := secretmanager.NewClient(ctx) if err != nil { return err } defer client.Close() // Access the secret version accessRequest := &secretmanager.AccessSecretVersionRequest{ Name: secretName, } result, err := client.AccessSecretVersion(ctx, accessRequest) if err != nil { return err } // Parse the secret data var secretData SecretData if err := json.Unmarshal(result.Payload.Data, &secretData); err != nil { return err } // You can now use the secretData fields as needed fmt.Printf("Variable1: %s\n", secretData.Variable1) fmt.Printf("Variable2: %s\n", secretData.Variable2) return nil } func main() { functions.RegisterHTTPFunction("/", retrieveSecretData) }
Make sure to replace
YOUR_PROJECT_ID
andYOUR_SECRET_NAME
with your actual Google Cloud project ID and secret name. -
Deploy your Cloud Function:
gcloud functions deploy retrieve-secret-data \ --runtime go116 \ --trigger-http \ --allow-unauthenticated
-
After deploying, you will receive a URL for your Cloud Function. You can invoke it using a web browser, curl, or any HTTP client.
This Cloud Function retrieves the secret data from Google Cloud Secret Manager, parses it as JSON, and prints the values of the specified variables. You can modify the SecretData
struct to match the structure of your secret JSON.