Detect variable from environment variable or GCP Secret Manager
You can access Secret Manager with a syntax similar to os.Getenv
Add IAM role roles/secretmanager.secretAccessor
to service account if necessary.
package main
import (
"context"
"github.com/sue445/gcp-secretmanagerenv"
)
func main() {
projectID := "gcp-project-id"
c, err := secretmanagerenv.NewClient(context.Background(), projectID)
if err != nil {
panic(err)
}
// get from environment variable
value, err := c.GetValueFromEnvOrSecretManager("SOME_KEY", true)
// => return value from environment variable or Secret Manager
// When key is not found in both environment variable and Secret Manager, returned empty string (not error)
value, err := c.GetValueFromEnvOrSecretManager("INVALID_KEY", false)
// => ""
// When key is not found in both environment variable and Secret Manager, returned error
value, err := c.GetValueFromEnvOrSecretManager("INVALID_KEY", true)
// => error
}
When c.GetValueFromEnvOrSecretManager(key, required)
is called, processing is performed in the following order
- Returns environment variable if
key
is found - Returns latest version value of Secret Manager if
projectID
isn't empty andkey
is found - Returns
""
ifrequired == false
- Returns
error
ifrequired == true
requires https://github.com/direnv/direnv
cp .envrc.example
vi .envrc
direnv allow