-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssmops.go
307 lines (261 loc) · 7.41 KB
/
ssmops.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
* Copyright 2018 Mark Adamcin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"github.com/aws/aws-sdk-go-v2/service/ssm"
"path"
"strings"
)
const KeyIdSuffix = "_SecureStringKeyId"
func findAllParametersForPath(ctx *CmdContext, paramPath string) ([]ssm.Parameter, error) {
var paramsForPath []ssm.Parameter
maxResults := int64(10)
recursive := false
withDecryption := true
input := ssm.GetParametersByPathInput{
MaxResults: &maxResults,
Path: ¶mPath,
WithDecryption: &withDecryption,
Recursive: &recursive}
request := ctx.Ssms.GetParametersByPathRequest(&input)
pager := request.Paginate()
for pager.Next() {
result := pager.CurrentPage()
if len(result.Parameters) > 0 {
paramsForPath = append(paramsForPath, result.Parameters...)
}
}
if pager.Err() != nil {
return paramsForPath, pager.Err()
} else {
return paramsForPath, nil
}
}
// If value is all spaces, subtract a space to reconstruct the original value for export.
func unescapeValueAfterGet(value string) string {
if len(value) == 0 {
return value
}
runes := []rune(value)
for _, ru := range runes {
if ru != rune(' ') {
return value
}
}
return string(runes[0: len(runes)-1])
}
// If value is the empty string or all spaces, add a space so the value is non-empty for SSM.
func escapeValueBeforePut(value string) string {
runes := []rune(value)
for _, ru := range runes {
if ru != rune(' ') {
return value
}
}
return value + " "
}
func getParamsPerPath(ctx *CmdContext, paramPath string, storeDict *map[string]string) error {
filterKey, _ := ssm.ParametersFilterKeyName.MarshalValue()
filterOption := "Equals"
paramsForPath, findErr := findAllParametersForPath(ctx, paramPath)
if findErr != nil {
return findErr
}
for _, param := range paramsForPath {
name := *param.Name
if param.Type == ssm.ParameterTypeStringList ||
(ctx.Prefs.NoGetSecureString && param.Type == ssm.ParameterTypeSecureString) {
continue
}
if !strings.HasPrefix(name, paramPath+"/") {
continue
}
storeKey := strings.TrimPrefix(name, paramPath+"/")
(*storeDict)[storeKey] = unescapeValueAfterGet(*param.Value)
if param.Type == ssm.ParameterTypeSecureString && ctx.Prefs.GetKeyId {
sidecarStoreKey := storeKey + KeyIdSuffix
input := ssm.DescribeParametersInput{}
input.ParameterFilters = append(input.ParameterFilters,
ssm.ParameterStringFilter{
Key: &filterKey,
Option: &filterOption,
Values: []string{name}})
result, err := ctx.Ssms.DescribeParametersRequest(&input).Send()
if err != nil {
return err
}
if len(result.Parameters) > 0 {
if result.Parameters[0].KeyId != nil {
(*storeDict)[sidecarStoreKey] = ctx.KmsMap.aliasFor(*result.Parameters[0].KeyId)
}
}
}
}
return nil
}
// Build an SSM parameter path or name.
// prefix: hierarchy levels 0-(N-2)
// filename: hierarchy level N-1 (.properties, .json, or .yaml extensions will be stripped)
// key: optional, hierarchy level N
// TODO make platform independent (i.e., this won't work on windows)
func buildParameterPath(prefix string, filename string, key string) string {
dir := prefix
if !strings.HasPrefix(dir, "/") {
dir = "/" + dir
}
fn := filename
if len(filename) == 0 {
fn = "$"
}
base := path.Join(prefix, fn)
realdir := path.Dir(base)
realfn := path.Base(base)
if len(realfn) > 0 && strings.ContainsRune(realfn, '.') {
fnRunes := []rune(realfn)
realfn = string(fnRunes[0:strings.LastIndex(realfn, ".")])
}
if len(key) > 0 {
return path.Join(realdir, realfn, key)
} else {
return path.Join(realdir, realfn)
}
}
func getParamsPerFile(ctx *CmdContext, filename string) error {
prefixes := ctx.Prefs.Prefixes
store := ctx.Stores[filename]
for _, prefix := range prefixes {
paramPath := buildParameterPath(prefix, filename, "")
if err := getParamsPerPath(ctx, paramPath, &store.Dict); err != nil {
return err
}
}
if len(store.Dict) > 0 {
return store.Save()
}
return nil
}
func clearParamsPerFile(ctx *CmdContext, filename string, prefix string) error {
paramPath := buildParameterPath(prefix, filename, "")
params, findErr := findAllParametersForPath(ctx, paramPath)
if findErr != nil {
return findErr
}
count := len(params)
names := make([]string, count)
i := 0
for _, param := range params {
names[i] = *param.Name
i++
}
batchSize := 10
batches := (count / batchSize) + 1
for b := 0; b < batches; b++ {
input := ssm.DeleteParametersInput{}
if b+1 < batches {
input.Names = append(input.Names, names[batchSize*b:batchSize*(b+1)]...)
} else {
input.Names = append(input.Names, names[batchSize*b:]...)
}
if len(input.Names) > 0 {
if _, err := ctx.Ssms.DeleteParametersRequest(&input).Send(); err != nil {
return err
}
}
}
return nil
}
func putParamsPerFile(ctx *CmdContext, filename string, prefix string) error {
if ctx.Prefs.ClearOnPut {
if err := clearParamsPerFile(ctx, filename, prefix); err != nil {
return err
}
}
store := ctx.Stores[filename]
for key, value := range store.Dict {
if strings.HasSuffix(key, KeyIdSuffix) {
continue
}
sidecarKeyId := key + KeyIdSuffix
name := buildParameterPath(prefix, filename, key)
keyId, isSecure := store.Dict[sidecarKeyId]
if isSecure && ctx.Prefs.NoPutSecureString {
continue
}
if len(ctx.Prefs.KeyIdPutAll) > 0 {
isSecure = true
keyId = ctx.Prefs.KeyIdPutAll
}
keyId = ctx.KmsMap.deref(keyId)
escaped := escapeValueBeforePut(value)
input := ssm.PutParameterInput{}
input.Name = &name
input.Value = &escaped
input.Overwrite = &ctx.Prefs.OverwritePut
if isSecure {
input.KeyId = &keyId
input.Type = ssm.ParameterTypeSecureString
} else {
input.Type = ssm.ParameterTypeString
}
_, err := ctx.Ssms.PutParameterRequest(&input).Send()
if err != nil {
return err
}
}
return nil
}
func deleteParamsPerFile(ctx *CmdContext, filename string, prefix string) error {
var names []string
store := ctx.Stores[filename]
for key := range store.Dict {
names = append(names, buildParameterPath(prefix, filename, key))
}
paramPath := buildParameterPath(prefix, filename, "")
allParams, findErr := findAllParametersForPath(ctx, paramPath)
if findErr != nil {
return findErr
}
var allNames []string
for _, param := range allParams {
allNames = append(allNames, *param.Name)
}
var toDelete []string
for _, cand := range names {
for _, name := range allNames {
if cand == name {
toDelete = append(toDelete, cand)
break
}
}
}
count := len(toDelete)
batchSize := 10
batches := (count / batchSize) + 1
for b := 0; b < batches; b++ {
input := ssm.DeleteParametersInput{}
if b+1 < batches {
input.Names = append(input.Names, names[batchSize*b:batchSize*(b+1)]...)
} else {
input.Names = append(input.Names, names[batchSize*b:]...)
}
if len(input.Names) > 0 {
if _, err := ctx.Ssms.DeleteParametersRequest(&input).Send(); err != nil {
return err
}
}
}
return nil
}