-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathput.go
279 lines (252 loc) · 6.72 KB
/
put.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
package commands
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/abiosoft/ishell"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/bwhaley/ssmsh/parameterstore"
)
// TODO Inline syntax
const putUsage string = `usage: put <newline>
Create or update parameters. Enter one option per line, ending with a blank line, or all
options inline. All fields except name, value, and type are optional.
Example of inline put:
/> put name=/House/Targaryen/Daenerys value="Queen" type="String" description="Mother of dragons"
Example of multiline put:
/>put
... name=/House/Lannister/Cersei
... value=Queen
... type=String
... description=Queen of the Seven Kingdoms
... key=arn:aws:kms:us-west-2:012345678901:key/321examp-ed00-427f-9729-748ba2254794
... overwrite=true
... pattern=[A-z]+
... tier=advanced
... policies=[policy1, policy2]
...
/>
Use the policy command to create named policy objects. Tier defaults to standard unless policies are defined.
`
var putParamInput ssm.PutParameterInput
var putParamRegion string
// Add or update parameters
func put(c *ishell.Context) {
var err error
var resp *ssm.PutParameterOutput
putParamInput = ssm.PutParameterInput{}
err = setDefaults(&putParamInput)
if err != nil {
shell.Println(err)
return
}
// Read args for values
var r bool
if len(c.Args) == 0 {
r = multiLinePut()
} else {
r = inlinePut(c.Args)
}
if !r {
return
}
if putParamInput.Name == nil ||
putParamInput.Value == nil ||
putParamInput.Type == nil {
shell.Println("Error: name, type and value are required.")
return
}
resp, err = ps.Put(&putParamInput, putParamRegion)
if err != nil {
shell.Println("Error: ", err)
} else {
version := strconv.Itoa(int(aws.Int64Value(resp.Version)))
if version != "" {
shell.Println("Put " + aws.StringValue(putParamInput.Name) + " version " + version)
}
}
}
// setDefaults sets parameter settings according to the defaults
func setDefaults(param *ssm.PutParameterInput) (err error) {
param.SetOverwrite(ps.Overwrite)
if ps.Key != "" {
param.SetKeyId(ps.Key)
}
param.SetType(ps.Type)
err = validateType(ps.Type)
if err != nil {
return err
}
putParamRegion = ps.Region
return nil
}
func multiLinePut() bool {
// Set the prompt explicitly rather than use SetMultiPrompt
// due to the unexpected 2nd line behavior
shell.SetPrompt("... ")
defer setPrompt(ps.Cwd)
shell.Println("Input options. End with a blank line.")
str := shell.ReadMultiLinesFunc(putOptions)
if str == "" {
shell.Println("multiline input ended in empty string")
return false
}
return true
}
func inlinePut(options []string) bool {
for _, p := range options {
if !putOptions(p) {
return false
}
}
return true
}
func putOptions(s string) bool {
if s == "" {
return false
}
paramOption := strings.Split(s, "=")
if len(paramOption) < 2 {
shell.Println("invalid input")
shell.Println(putUsage)
return false
}
field := strings.ToLower(paramOption[0])
val := strings.Join(paramOption[1:], "=") // Handles the case where a value has an "=" character
err := validate(field, val)
if err != nil {
shell.Println(err)
return false
}
return true
}
func validate(f, v string) (err error) {
m := map[string]func(string) error{
"type": validateType,
"name": validateName,
"value": validateValue,
"description": validateDescription,
"key": validateKey,
"pattern": validatePattern,
"overwrite": validateOverwrite,
"region": validateRegion,
"tier": validateTier,
"policies": validatePolicies,
}
if validator, ok := m[strings.ToLower(f)]; ok {
err = validator(v)
if err != nil {
// A validator failed so we need to reset the parameter input to an empty state
putParamInput = ssm.PutParameterInput{}
shell.Println(putUsage)
return err
}
}
return nil
}
func validateType(s string) (err error) {
validTypes := []string{"String", "StringList", "SecureString"}
for i := 0; i < len(validTypes); i++ {
if strings.EqualFold(s, validTypes[i]) { // Case insensitive validation of type field
putParamInput.Type = aws.String(validTypes[i])
return nil
}
}
return fmt.Errorf("Invalid type %s", s)
}
func validateValue(s string) (err error) {
s = trimSpaces(s)
putParamInput.Value = aws.String(s)
return nil
}
// trimSpaces works around an issue in ishell where a space is added to the end of each line in a multiline value
// https://github.com/abiosoft/ishell/issues/132
func trimSpaces(s string) string {
parts := strings.Split(s, "\n")
for i := 0; i < len(parts)-1; i++ {
size := len(parts[i])
parts[i] = parts[i][:size-1]
}
return strings.Join(parts, "\n")
}
func validateName(s string) (err error) {
if strings.HasPrefix(s, parameterstore.Delimiter) {
putParamInput.SetName(s)
} else {
putParamInput.SetName(ps.Cwd + parameterstore.Delimiter + s)
}
return nil
}
func validateDescription(s string) (err error) {
putParamInput.SetDescription(s)
return nil
}
// TODO validate key
func validateKey(s string) (err error) {
putParamInput.SetKeyId(s)
return nil
}
// TODO validate pattern
func validatePattern(s string) (err error) {
putParamInput.SetAllowedPattern(s)
return nil
}
func validateOverwrite(s string) (err error) {
overwrite, err := strconv.ParseBool(s)
if err != nil {
shell.Println("overwrite must be true or false")
return err
}
putParamInput.SetOverwrite(overwrite)
return nil
}
func validateRegion(s string) (err error) {
putParamRegion = s
return nil
}
const (
StandardTier = "Standard"
AdvancedTier = "Advanced"
)
func validateTier(s string) (err error) {
if strings.ToLower(s) == StandardTier || strings.ToLower(s) == AdvancedTier {
putParamInput.Tier = aws.String(strings.Title(s))
return nil
}
return errors.New("tier must be standard or advanced")
}
func validatePolicies(s string) (err error) {
var policySet []Policies
re := regexp.MustCompile(`^\[([\w\s,]+)\]`)
p := re.FindStringSubmatch(s)
if len(p) != 2 {
return fmt.Errorf("unable to validate policies %s", s)
}
namedPolicies := trim(strings.Split(p[1], ","))
for _, p := range namedPolicies {
policy, present := policies[p]
if !present {
return fmt.Errorf("policy %q does not exist. add it with the policy command", p)
}
if policy.expiration != (Expiration{}) {
policySet = append(policySet, policy.expiration)
}
for i := range policy.expirationNotification {
policySet = append(policySet, policy.expirationNotification[i])
}
for i := range policy.noChangeNotification {
policySet = append(policySet, policy.noChangeNotification[i])
}
}
policyBytes, err := json.Marshal(policySet)
if err != nil {
return err
}
putParamInput.Policies = aws.String(string(policyBytes))
putParamInput.Tier = aws.String(AdvancedTier)
return nil
}