forked from Droplr/aws-env
-
Notifications
You must be signed in to change notification settings - Fork 8
/
aws-env.go
210 lines (168 loc) · 4.58 KB
/
aws-env.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
jsoniter "github.com/json-iterator/go" //native json lib doesn't support marshalling map[interface{}]interface{}
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/kataras/golog"
)
type dict map[interface{}]interface{}
var version string
func main() {
if len(os.Args) > 1 {
if os.Args[1] == "-v" {
fmt.Printf("awsenv version %s\n", version)
os.Exit(0)
}
}
// Set log level if defind, default level info
if os.Getenv("LOG_LEVEL") != "" {
golog.SetLevel(os.Getenv("LOG_LEVEL"))
}
keys := strings.Split(os.Getenv("SSM_PATH"), "/")
params := make(map[string]string)
// Remove the empty string created by the split
if keys[0] == "" {
keys = keys[1:]
}
path := ""
// Loop through the sub paths and retrieve parameters
for i := range keys {
path = path + "/" + keys[i]
golog.Infof("Retrieving parameters in path %s", path)
ExportVariables(path, "", params)
}
toStdout := strings.ToLower(os.Getenv("TO_STDOUT"))
if toStdout == "true" {
ParametersToStdout(params)
} else {
ParametersToFile(params)
}
}
func CreateClient() *ssm.SSM {
maxRetries := GetEnv("AWSENV_MAX_RETRIES", "3")
maxRetriesInt, _ := strconv.Atoi(maxRetries)
config := &aws.Config{MaxRetries: aws.Int(maxRetriesInt)}
session := session.Must(session.NewSession(config))
return ssm.New(session)
}
func ExportVariables(path string, nextToken string, params map[string]string) {
client := CreateClient()
input := &ssm.GetParametersByPathInput{
Path: &path,
WithDecryption: aws.Bool(true),
}
if nextToken != "" {
input.SetNextToken(nextToken)
}
output, err := client.GetParametersByPath(input)
if err != nil {
golog.Fatal(err)
}
for _, element := range output.Parameters {
env, value := TrimParameter(path, element)
golog.Debugf("Found parameter %s in path %s", env, path)
params[env] = value
}
if output.NextToken != nil {
ExportVariables(path, *output.NextToken, params)
}
}
func TrimParameter(path string, parameter *ssm.Parameter) (string, string) {
name := *parameter.Name
value := *parameter.Value
env := strings.Trim(name[len(path):], "/")
value = strings.Replace(value, "\n", "\\n", -1)
return env, value
}
func ParametersToStdout(params map[string]string) {
golog.Debug("Printing params to stdout")
for key, value := range params {
key = strings.ToUpper(key)
fmt.Printf("export %s=$'%s'\n", key, value)
}
}
func ParametersToFile(params map[string]string) {
var fileContent []byte
format := GetEnv("FORMAT", "export")
if format == "json" {
fileContent = ParametersToJson(params)
} else if format == "json-nested" {
fileContent = ParametersToNestedJson(params)
} else {
fileContent = ParametersToFormattedString(format, params)
}
dir := GetEnv("DIRECTORY", "/ssm")
// Create directory if it doesn't exist
if _, err := os.Stat(dir); os.IsNotExist(err) {
golog.Debugf("Creating directory %s", dir)
os.MkdirAll(dir, 0755)
}
filename := GetEnv("AWSENV_FILENAME", ".env")
golog.Debugf("Writing params to %s/%s", dir, filename)
err := ioutil.WriteFile(dir+"/"+filename, fileContent, 0744)
if err != nil {
golog.Fatal(err)
}
}
func ParametersToJson(params map[string]string) []byte {
json, err := jsoniter.MarshalIndent(params, "", " ")
if err != nil {
golog.Fatal(err)
}
return json
}
func ParametersToNestedJson(params map[string]string) []byte {
nestedParams := make(dict)
for key, value := range params {
keys := strings.Split(key, "_")
SetNestedParamKeys(nestedParams, keys, value)
}
json, err := jsoniter.MarshalIndent(nestedParams, "", " ")
if err != nil {
golog.Fatal(err)
}
return json
}
func SetNestedParamKeys(d dict, keys []string, value string) {
if len(keys) == 1 {
d[keys[0]] = value
return
}
v, ok := d[keys[0]]
if !ok {
v = dict{}
d[keys[0]] = v
}
SetNestedParamKeys(v.(dict), keys[1:], value)
}
func ParametersToFormattedString(format string, params map[string]string) []byte {
var buffer bytes.Buffer
for key, value := range params {
buffer.WriteString(FormatParameter(key, value, format))
}
return buffer.Bytes()
}
func FormatParameter(key string, value string, format string) string {
switch format {
case "shell":
return fmt.Sprintf("%s='%s'\n", key, value)
case "unquoted-shell":
return fmt.Sprintf("%s=%s\n", key, value)
default:
return fmt.Sprintf("export %s=$'%s'\n", key, value)
}
}
func GetEnv(envvar string, defaultValue string) string {
value, exists := os.LookupEnv(envvar)
if !exists {
return defaultValue
}
return value
}