Select Git revision
secrets_manager.go
secrets_manager.go 4.18 KiB
package secrets_manager
import (
"encoding/base64"
"os"
"gitlab.com/uafrica/go-utils/logs"
"gitlab.com/uafrica/go-utils/struct_utils"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/aws/aws-secretsmanager-caching-go/secretcache"
)
type DatabaseCredentials struct {
Username string `json:"username"`
Password string `json:"password"`
Engine string `json:"engine"`
Host string `json:"host"`
Port int `json:"port"`
InstanceIdentifier string `json:"dbInstanceIdentifier"`
}
var (
secretCache, _ = secretcache.New()
secretManagerRegion = "af-south-1"
)
func GetDatabaseCredentials(secretID string, isDebug bool) (DatabaseCredentials, error) {
secret, _ := getSecret(secretID, isDebug)
var credentials DatabaseCredentials
err := struct_utils.UnmarshalJSON([]byte(secret), &credentials)
if err != nil {
return DatabaseCredentials{}, err
}
return credentials, nil
}
func getSecret(secretID string, isDebug bool) (string, string) {
cachedSecret, err := secretCache.GetSecretString(secretID)
if err != nil {
logs.Info("Failed to get secret key from cache")
}
if cachedSecret != "" {
return cachedSecret, ""
}
awsSession := session.New()
// Get local config
if isDebug && os.Getenv("ENVIRONMENT") != "" {
logs.Info("Using access key %s", os.Getenv("AWS_ACCESS_KEY_ID"))
awsSession, err = session.NewSessionWithOptions(session.Options{
Config: aws.Config{
Region: aws.String("af-south-1"),
CredentialsChainVerboseErrors: aws.Bool(true),
},
})
if err != nil {
return "", ""
}
}
// Create a Secrets Manager client
svc := secretsmanager.New(awsSession, aws.NewConfig().WithRegion(secretManagerRegion))
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(string(secretID)),