Managing Secret For Your Golang Apps With The GCP Secret Manager
<p><a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2Fformat%3Awebp%2F0%2A6M2UM2lycBT1iEMp" class="article-body-image-wrapper"><img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A1400%2Fformat%3Awebp%2F0%2A6M2UM2lycBT1iEMp" alt="Photo by Aneta Pawlik on Unsplash" width="1400" height="933"></a></p> <p>While developing a serverless application and having a secret key in JSON format, I always looked at how we store that file securely. We can’t save the JSON file in our public repository, right? ☠️</p> <p>Since I plan to deploy the application using Google Cloud Run,
While developing a serverless application and having a secret key in JSON format, I always looked at how we store that file securely. We can’t save the JSON file in our public repository, right? ☠️
Since I plan to deploy the application using Google Cloud Run, I’ve found that Google Cloud has a Secret Manager service!
Store API keys, passwords, certificates, and sensitive data
Secret Manager is a secure and convenient storage system for API keys, passwords, certificates, and other sensitive data
- Google Cloud
With Secret Manager, we can store the credentials to the Secret Manager and integrate our application to “take” the credentials from the Secret Manager.
There are two ways to store the secret, we can use the console or CLI, for this time I will use the CLI.
For example, I have a simple Golang app that has a file called secret-key.json for authentication to database services. I want to deploy the application using Cloud Run and using the secret key that is provided so the service can communicated to the database.
I already downloaded the key and am ready to put it on Secret Manager. First of all, make sure your devices are already authenticated with your Google Cloud account.
You can log in to your account by using this command
gcloud auth login
Enter fullscreen mode
Exit fullscreen mode
After that, set to using your project
gcloud config set project
Enter fullscreen mode
Exit fullscreen mode
The next step is we should enable the API of the Secret Manager service. You can use this command to enable it.
gcloud services enable secretmanager.googleapis.com
Enter fullscreen mode
Exit fullscreen mode
If the message returns “Operation …….. finished successfully” now we’re ready to go 🚀
Now, we’re heading to the directory where we store the secret key, or you can use any directory and set it the path on the command, here is the command that we will use
gcloud secrets create --data-file=
Enter fullscreen mode
Exit fullscreen mode
The image below shows the results if we already created the secret in Secret Manager.
Or you can check it from the Google Cloud Console and go to the Secret Manager page.
Now this is the Go code looks alike, since we just need to read the data, the process on this code is just to retrieve the secret. You should fill out the GOOGLE_CLOUD_PROJECT_NUMBER you can hardcode it or use OS Env.
package main import ( "context" "log" secretsmanager "cloud.google.com/go/secretmanager/apiv1" "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" ) func main() { projectNumber := os.Getenv("GOOGLE_CLOUD_PROJECT_NUMBER") secretName := os.Getenv("SECRET_NAME") ctx := context.Background() client, err := secretsmanager.NewClient(ctx) if err != nil { log.Fatalf("failed to setup client: %v", err) } defer client.Close() accessRequest := &secretmanagerpb.AccessSecretVersionRequest{ Name: "projects/" + projectNumber + "/secrets/" + secretName + "/versions/latest", } result, err := client.AccessSecretVersion(ctx, accessRequest) if err != nil { log.Fatalf("failed to access secret version: %v", err) } secret := string(result.Payload.Data) log.Printf("secret: %s", secret) }package main import ( "context" "log" secretsmanager "cloud.google.com/go/secretmanager/apiv1" "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" ) func main() { projectNumber := os.Getenv("GOOGLE_CLOUD_PROJECT_NUMBER") secretName := os.Getenv("SECRET_NAME") ctx := context.Background() client, err := secretsmanager.NewClient(ctx) if err != nil { log.Fatalf("failed to setup client: %v", err) } defer client.Close() accessRequest := &secretmanagerpb.AccessSecretVersionRequest{ Name: "projects/" + projectNumber + "/secrets/" + secretName + "/versions/latest", } result, err := client.AccessSecretVersion(ctx, accessRequest) if err != nil { log.Fatalf("failed to access secret version: %v", err) } secret := string(result.Payload.Data) log.Printf("secret: %s", secret) }Enter fullscreen mode
Exit fullscreen mode
While running it locally, don’t forget to authenticate the program with the Google Cloud Project by using this command. For more reference, you can check this out.
gcloud auth application-default login
Enter fullscreen mode
Exit fullscreen mode
Then, you can run the program using go run main.go and here we go, this is the secret that we stored it before!
If you want to deploy it to Cloud Run, you can try this code
package main import ( "context" "fmt" "log" "net/http" "os" secretsmanager "cloud.google.com/go/secretmanager/apiv1" "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" ) func main() { projectNumber := os.Getenv("GOOGLE_CLOUD_PROJECT_NUMBER") secretName := os.Getenv("SECRET_NAME") ctx := context.Background() client, err := secretsmanager.NewClient(ctx) if err != nil { log.Fatalf("failed to setup client: %v", err) } defer client.Close() accessRequest := &secretmanagerpb.AccessSecretVersionRequest{ Name: "projects/" + projectNumber + "/secrets/" + secretName + "/versions/latest", } result, err := client.AccessSecretVersion(ctx, accessRequest) if err != nil { log.Fatalf("failed to access secret version: %v", err) } secret := string(result.Payload.Data) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Your secret is: %s", secret) }) log.Fatal(http.ListenAndServe(":8080", nil)) }package main import ( "context" "fmt" "log" "net/http" "os" secretsmanager "cloud.google.com/go/secretmanager/apiv1" "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" ) func main() { projectNumber := os.Getenv("GOOGLE_CLOUD_PROJECT_NUMBER") secretName := os.Getenv("SECRET_NAME") ctx := context.Background() client, err := secretsmanager.NewClient(ctx) if err != nil { log.Fatalf("failed to setup client: %v", err) } defer client.Close() accessRequest := &secretmanagerpb.AccessSecretVersionRequest{ Name: "projects/" + projectNumber + "/secrets/" + secretName + "/versions/latest", } result, err := client.AccessSecretVersion(ctx, accessRequest) if err != nil { log.Fatalf("failed to access secret version: %v", err) } secret := string(result.Payload.Data) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Your secret is: %s", secret) }) log.Fatal(http.ListenAndServe(":8080", nil)) }Enter fullscreen mode
Exit fullscreen mode
go-gcp-secret
Don’t forget to put the Env Variables while setting up the Cloud Run deployment.
If the deployment succeeds, you can try to call the “/” endpoint, and it will return the secret key that we need.
Additionally, if the Cloud Run needs access to the Secret Manager, you can go to the Secret Manager and give access to your Cloud Run Service Account by clicking Add Principal.
That’s all! 🚀 Thanks for reading!
DEV Community
https://dev.to/gdg/managing-secret-for-your-golang-apps-with-the-gcp-secret-manager-3gljSign in to highlight and annotate this article

Conversation starters
Daily AI Digest
Get the top 5 AI stories delivered to your inbox every morning.
More about
versionproductapplicationExclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT - WSJ
<a href="https://news.google.com/rss/articles/CBMiogNBVV95cUxNUmZFSTU1Z01Ed0E5YVBGRFFLUFFVMXVHb0VkZUo5TGpDWHZTT1l1VlRRQlIxRG12UGl1OUdHbUlkdDZCMHlzeEJrTlMxQXNpd1R5aWJHV2V6czJXdFVSRDdhaUI3VDZRMUFXZUw3U2lPQ3l1YWxRVmNWLVZNYXlIdTFaaUZKV2kwT1cwTDJpeU91ZUl2bEotSVJXSVhybTRmaFd1XzFoRXRQQ0J6SWxuNkdyd2oyN05YU0I2YW9YeGlzUG1XdldQZkd0cV9aazhwekhIb280a2V3T3l4NUJwaS1yUFVIWHJERC11MEx2T21iYjVvN0hFdU1XVVJvRmdaQWNReVN5WXJkRXI1S052ZU42VTlOM0Z5dk4yRllmaGdlc09zalZmWXFTUjBKMW1Ca3JuTDEzR2lkX3Nta1dHcFdRMHd6eHUzS1BZN0YtdGl0NXlDQk1nSnlpX2x5U0RwSTdjRTM3OFRUbGlzZDdZNWZSdXgyZEFoXzBoLVU5TXl2SVlDZTZ6LUxxZWlTUTJHMnotUzdsVzBWbnVrdk03QTVn?oc=5" target="_blank">Exclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT</a> <font color="#6f6f6f">WSJ</font>
Exclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT - WSJ
<a href="https://news.google.com/rss/articles/CBMiogNBVV95cUxPT2ZpR2h0a1pTMjF2dVhVOVItMnNQMUhka1RFd0pGWXdBN2lsUXluVU5tUThQWEJjMVZicWFDNUYxNWxPelFkM0pidV9oQ0l1NkJ2a1FQUGNtSWx5Q0dSQmVOMUt5LWc3ZWxBYS1tWUVrbFVjWTA3T3RpZmlBNV9fUWI2T0g2SUZMSEJGSXRaVVRseDVTcHRJWTIzQm1pY0xSY0l5OXlJYjYwRk5UREo2ajFCbFVZdV9vaGxYeGQwbzZiLUJBeGVsZE1heVFyOXFwMVU5YXFoTlFLZWZ5LWpzT3B4blFkZnJGSHF1aG1YMzAtQy15UUVmSmpSZ2Q1dFVCdDNtSG9qSU5Mc3duVWdnQnJ0a2RSWHRoNklJQTl6X1RkeVpfOThFNGJuUkdtT1dNWldrZVpvdldSUWdOYTM4bEgwenJqaVM1dlFMSTA3YkM0YmZNTk5VQ1I0ZHFWVElSX0FNelhVOGJBTVRnNjVlUUVOcFAzQ0l0d3dYR19Va2NhWEMzeGhvX3VibDBTQ0JMN2dqbC13SVVmNzlIbkdrcUJn?oc=5" target="_blank">Exclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT</a> <font color="#6f6f6f">WSJ</font>
Exclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT - WSJ
<a href="https://news.google.com/rss/articles/CBMiogNBVV95cUxQQzRxLW51R21SWVJSX2NjUnNaYWEyd1dQVlBxclQ1bWxReU5oZW1paDFlbnpZRGRTWGQ0WnhWSjF2N2ZaeEVWdnpHQXhsV2dXc2FPUGc4dXp5aWhXTWFvN0I4UzJPbnVJb0RGVHluSkdHeXBZVkd0d3N4MWVkSG1oV242bGFPX3FmcGplNGNQSUdsMncwTE5LNVpUTEZLT29xOHhCS0tJU3pjZ0ktYU1rWWF6Y1JBeUI2Q0RBeGdDaVNTWWljcGtNLVpWcUkyVkhyUmVtanhHWDRHYjdqblV2aDFaYW9BRkdrUE03M1pNNE1qdHRTYlJKTno3cmhOVHhWNE53ZTFvMjVyMWR1ajBDRFlKVnpYa1RyUkhRb1ZILTkzRm9WSGdOZlZMZVRFQk1EU2xaSHBNWUlTZzRYRkYxNklTaXpNMlBOZGNBU29FREpBVkFCVkM5eks2cFhwaFFKNWlINzZNSFIwcGdPTDFKS053X0RsYWZfbWFERFN1SUV3TldPbjNwU2dXRFdMazhTTW1xaURpNWZCR0VKZEhTS25n?oc=5" target="_blank">Exclusive | The Sudden Fall of OpenAI’s Most Hyped Product Since ChatGPT</a> <font color="#6f6f6f">WSJ</font>
Knowledge Map
Connected Articles — Knowledge Graph
This article is connected to other articles through shared AI topics and tags.
More in Products
OpenAI raises record US$122 billion, paving way for superapp pivot - digitimes
<a href="https://news.google.com/rss/articles/CBMioAFBVV95cUxQTmlRb0Q1Wm1xdzFfT3NNUlVZWWZaZE9LaUdtSXFoWWplUHJLbUhXcDM3VDVWNkF2NmtCR3pFcXRER05QSG8tVy1ON1BpNUdMUWxTVi1sRGM2TkpRZ0VSbXNEek5fMEU1MEZIR1RnQ2h0QndCeTVLRndpMm5iaFRIelprUHNTT0RCZmVaNUJuNTJieDNQNUpza3JGaFNnaXVj?oc=5" target="_blank">OpenAI raises record US$122 billion, paving way for superapp pivot</a> <font color="#6f6f6f">digitimes</font>
Orange Lion Sports Ushers in Sports Industry's "Agent Era" with Debut of AI Event Operations Assistant - The Korea Herald
<a href="https://news.google.com/rss/articles/CBMiV0FVX3lxTE9ZTElrcUZOckY5ZVhYV25jSXVvQndKUnF5cExnRzhGb3F1SWN4SjMyV0Q2X3ZQNmJFUFpPVnpwZlQyMUZCZGZlUmEyNFB1eENfcUwxNUpfQQ?oc=5" target="_blank">Orange Lion Sports Ushers in Sports Industry's "Agent Era" with Debut of AI Event Operations Assistant</a> <font color="#6f6f6f">The Korea Herald</font>
OpenAI raises $122B and focuses on an AI superapp - Techzine Global
<a href="https://news.google.com/rss/articles/CBMinwFBVV95cUxOUm1FRnpGeEpSbHd1NnZmR0ZVSlBVWlFUNEtEbU5hMEpKX0pJNkxpSGlQdXRCaVJvOWdFeXlXanRlcHBOVjdjbHo4Z3FLcTVZVWpNTG9GNlVtOHZBanl0dEN1dFhhcnNmazd3SWxDTVMteGU1LU5SMklaRXNvcHNZek1TN0FTaVJkVmpPVmVyZERUQ0xJdHg0amNzLVhqZ00?oc=5" target="_blank">OpenAI raises $122B and focuses on an AI superapp</a> <font color="#6f6f6f">Techzine Global</font>
New AI tool fights back against speech eavesdropping - EurekAlert!
<a href="https://news.google.com/rss/articles/CBMiXEFVX3lxTE5qSWhWOVVWaFVxY3ItUkx3dWVzb2RwcEpxM29RTUVnX3Zmb2FrMXZlbXJ6R0dDc2gya2FxM0ZxRE9FN0dXOXV3V1VaRzExZkloem9Vd1VOYllJOVdU?oc=5" target="_blank">New AI tool fights back against speech eavesdropping</a> <font color="#6f6f6f">EurekAlert!</font>

Discussion
Sign in to join the discussion
No comments yet — be the first to share your thoughts!