Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (71 loc) · 1.9 KB
/
Copy pathmain.go
File metadata and controls
87 lines (71 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
)
func main() {
secretName := os.Args[1]
appConfig := getFromSecretsManager(secretName)
envVars := convertToEnvVarStatements(appConfig)
for line := range envVars {
fmt.Println(line)
}
}
func getFromSecretsManager(secretName string) map[string]string {
config, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
log.Fatal(err)
}
svc := secretsmanager.NewFromConfig(config)
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(secretName),
VersionStage: aws.String("AWSCURRENT"),
}
result, err := svc.GetSecretValue(context.TODO(), input)
if err != nil {
log.Fatal(err.Error())
}
appConfig := map[string]string{}
err = json.Unmarshal([]byte(*result.SecretString), &appConfig)
if err != nil {
log.Fatal(err.Error())
}
return appConfig
}
func convertToEnvVarStatements(config map[string]string) []string {
var output []string
for key, val := range config {
line := fmt.Sprintf(
"export %s=%s",
sanitizeKey(key),
sanitizeValue(val),
)
line = sanitizeLine(line)
output = append(output, line)
}
return output
}
// sanitizeLine will remove known dangerous characters from the entire line
func sanitizeLine(line string) string {
return line
}
// santizeKey will format the key in a format valid for environment variables
func sanitizeKey(key string) string {
key = strings.ToUpper(key)
key = strings.ReplaceAll(key, " ", "_")
key = strings.ReplaceAll(key, "-", "_")
return key
}
// sanitizeValue will perform any sanitization which cannot happen at a line level
func sanitizeValue(value string) string {
// Always quote the value - this handles spaces, but also a lot of bad characters
value = fmt.Sprintf("\"%s\"", value)
return value
}