gcp-secretmanagerenv
Detect variable from environment variable or GCP Secret Manager
You can access Secret Manager with a syntax similar to os.Getenv
Requirements
Add IAM role roles/secretmanager.secretAccessor
to service account if necessary.
Usage
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
}
Specification
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 and key
is found
- Returns
""
if required == false
- Returns
error
if required == true
Development
Setup
requires https://github.com/direnv/direnv
cp .envrc.example
vi .envrc
direnv allow