forked from remind101/ssm-env
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
233 lines (189 loc) · 4.97 KB
/
main.go
File metadata and controls
233 lines (189 loc) · 4.97 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package main
import (
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"text/template"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"
)
const (
// DefaultTemplate is the default template used to determine what the SSM
// parameter name is for an environment variable.
DefaultTemplate = `{{ if hasPrefix .Value "ssm://" }}{{ trimPrefix .Value "ssm://" }}{{ end }}`
// defaultBatchSize is the default number of parameters to fetch at once.
// The SSM API limits this to a maximum of 10 at the time of writing.
defaultBatchSize = 10
)
// TemplateFuncs are helper functions provided to the template.
var TemplateFuncs = template.FuncMap{
"contains": strings.Contains,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"trimPrefix": strings.TrimPrefix,
"trimSuffix": strings.TrimSuffix,
"trimSpace": strings.TrimSpace,
"trimLeft": strings.TrimLeft,
"trimRight": strings.TrimRight,
"trim": strings.Trim,
"title": strings.Title,
"toTitle": strings.ToTitle,
"toLower": strings.ToLower,
"toUpper": strings.ToUpper,
}
func main() {
var (
template = flag.String("template", DefaultTemplate, "The template used to determine what the SSM parameter name is for an environment variable. When this template returns an empty string, the env variable is not an SSM parameter")
decrypt = flag.Bool("with-decryption", false, "Will attempt to decrypt the parameter, and set the env var as plaintext")
)
flag.Parse()
args := flag.Args()
if len(args) <= 0 {
flag.Usage()
os.Exit(1)
}
path, err := exec.LookPath(args[0])
must(err)
var os osEnviron
t, err := parseTemplate(*template)
must(err)
e := &expander{
batchSize: defaultBatchSize,
t: t,
ssm: ssm.New(session.New()),
os: os,
}
must(e.expandEnviron(*decrypt))
must(syscall.Exec(path, args[0:], os.Environ()))
}
func parseTemplate(templateText string) (*template.Template, error) {
return template.New("template").Funcs(TemplateFuncs).Parse(templateText)
}
type ssmClient interface {
GetParameters(*ssm.GetParametersInput) (*ssm.GetParametersOutput, error)
}
type environ interface {
Environ() []string
Setenv(key, vale string)
}
type osEnviron int
func (e osEnviron) Environ() []string {
return os.Environ()
}
func (e osEnviron) Setenv(key, val string) {
os.Setenv(key, val)
}
type ssmVar struct {
envvar string
parameter string
}
type expander struct {
t *template.Template
ssm ssmClient
os environ
batchSize int
}
func (e *expander) parameter(k, v string) (*string, error) {
b := new(bytes.Buffer)
if err := e.t.Execute(b, struct{ Name, Value string }{k, v}); err != nil {
return nil, err
}
if p := b.String(); p != "" {
return &p, nil
}
return nil, nil
}
func (e *expander) expandEnviron(decrypt bool) error {
// Environment variables that point to some SSM parameters.
var ssmVars []ssmVar
uniqNames := make(map[string]bool)
for _, envvar := range e.os.Environ() {
k, v := splitVar(envvar)
parameter, err := e.parameter(k, v)
if err != nil {
return fmt.Errorf("determining name of parameter: %v", err)
}
if parameter != nil {
uniqNames[*parameter] = true
ssmVars = append(ssmVars, ssmVar{k, *parameter})
}
}
if len(uniqNames) == 0 {
// Nothing to do, no SSM parameters.
return nil
}
names := make([]string, len(uniqNames))
i := 0
for k := range uniqNames {
names[i] = k
i++
}
for i := 0; i < len(names); i += e.batchSize {
j := i + e.batchSize
if j > len(names) {
j = len(names)
}
values, err := e.getParameters(names[i:j], decrypt)
if err != nil {
return err
}
for _, v := range ssmVars {
val, ok := values[v.parameter]
if ok {
e.os.Setenv(v.envvar, val)
}
}
}
return nil
}
func (e *expander) getParameters(names []string, decrypt bool) (map[string]string, error) {
values := make(map[string]string)
input := &ssm.GetParametersInput{
WithDecryption: aws.Bool(decrypt),
}
for _, n := range names {
input.Names = append(input.Names, aws.String(n))
}
resp, err := e.ssm.GetParameters(input)
if err != nil {
return values, err
}
if len(resp.InvalidParameters) > 0 {
return values, newInvalidParametersError(resp)
}
for _, p := range resp.Parameters {
values[*p.Name] = *p.Value
}
return values, nil
}
type invalidParametersError struct {
InvalidParameters []string
}
func newInvalidParametersError(resp *ssm.GetParametersOutput) *invalidParametersError {
e := new(invalidParametersError)
for _, p := range resp.InvalidParameters {
if p == nil {
continue
}
e.InvalidParameters = append(e.InvalidParameters, *p)
}
return e
}
func (e *invalidParametersError) Error() string {
return fmt.Sprintf("invalid parameters: %v", e.InvalidParameters)
}
func splitVar(v string) (key, val string) {
parts := strings.Split(v, "=")
return parts[0], parts[1]
}
func must(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "ssm-env: %v\n", err)
os.Exit(1)
}
}