-
Notifications
You must be signed in to change notification settings - Fork 394
/
secret_init.go
519 lines (446 loc) · 15 KB
/
secret_init.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/aws/aws-sdk-go/aws"
awsssm "github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/copilot-cli/internal/pkg/aws/identity"
"github.com/aws/copilot-cli/internal/pkg/aws/sessions"
"github.com/aws/copilot-cli/internal/pkg/aws/ssm"
"github.com/aws/copilot-cli/internal/pkg/config"
"github.com/aws/copilot-cli/internal/pkg/deploy"
"github.com/aws/copilot-cli/internal/pkg/describe"
"github.com/aws/copilot-cli/internal/pkg/template"
"github.com/aws/copilot-cli/internal/pkg/term/color"
"github.com/aws/copilot-cli/internal/pkg/term/log"
"github.com/aws/copilot-cli/internal/pkg/term/prompt"
"github.com/aws/copilot-cli/internal/pkg/term/selector"
"github.com/aws/copilot-cli/internal/pkg/workspace"
"github.com/dustin/go-humanize/english"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
)
const (
fmtSecretParameterName = "/copilot/%s/%s/secrets/%s"
fmtSecretParameterNameMftExample = "/copilot/${COPILOT_APPLICATION_NAME}/${COPILOT_ENVIRONMENT_NAME}/secrets/%s"
)
const (
secretInitAppPrompt = "Which application do you want to add the secret to?"
secretInitAppPromptHelp = "The secret can then be versioned by your existing environments inside the application."
secretInitSecretNamePrompt = "What would you like to name this secret?"
secretInitSecretNamePromptHelp = "The name of the secret, such as 'db_password'."
fmtSecretInitSecretValuePrompt = "What is the value of secret %s in environment %s?"
fmtSecretInitSecretValuePromptHelp = "If you do not wish to add the secret %s to environment %s, you can leave this blank by pressing 'Enter' without entering any value."
)
type secretInitVars struct {
appName string
name string
values map[string]string
inputFilePath string
overwrite bool
}
type secretInitOpts struct {
secretInitVars
shouldShowOverwriteHint bool
secretValues map[string]map[string]string
store store
fs afero.Fs
prompter prompter
selector appSelector
ws wsEnvironmentsLister
envCompatibilityChecker map[string]versionCompatibilityChecker
secretPutters map[string]secretPutter
configureClientsForEnv func(envName string) error
readFile func() ([]byte, error)
}
func newSecretInitOpts(vars secretInitVars) (*secretInitOpts, error) {
sessProvider := sessions.ImmutableProvider(sessions.UserAgentExtras("secret init"))
defaultSession, err := sessProvider.Default()
if err != nil {
return nil, err
}
fs := afero.NewOsFs()
ws, err := workspace.Use(afero.NewOsFs())
if err != nil {
return nil, err
}
store := config.NewSSMStore(identity.New(defaultSession), awsssm.New(defaultSession), aws.StringValue(defaultSession.Config.Region))
prompter := prompt.New()
opts := secretInitOpts{
secretInitVars: vars,
store: store,
fs: fs,
ws: ws,
envCompatibilityChecker: make(map[string]versionCompatibilityChecker),
secretPutters: make(map[string]secretPutter),
prompter: prompter,
selector: selector.NewAppEnvSelector(prompter, store),
}
opts.configureClientsForEnv = func(envName string) error {
checker, err := describe.NewEnvDescriber(describe.NewEnvDescriberConfig{
App: opts.appName,
Env: envName,
ConfigStore: opts.store,
})
if err != nil {
return fmt.Errorf("new environment compatibility checker: %v", err)
}
opts.envCompatibilityChecker[envName] = checker
env, err := opts.targetEnv(envName)
if err != nil {
return err
}
sess, err := sessProvider.FromRole(env.ManagerRoleARN, env.Region)
if err != nil {
return fmt.Errorf("create session from environment manager role %s in region %s: %w", env.ManagerRoleARN, env.Region, err)
}
opts.secretPutters[envName] = ssm.New(sess)
return nil
}
opts.readFile = func() ([]byte, error) {
file, err := opts.fs.Open(opts.inputFilePath)
if err != nil {
return nil, fmt.Errorf("open input file %s: %w", opts.inputFilePath, err)
}
defer file.Close()
f, err := afero.ReadFile(opts.fs, file.Name())
if err != nil {
return nil, fmt.Errorf("read input file %s: %w", opts.inputFilePath, err)
}
return f, nil
}
return &opts, nil
}
// Validate returns an error if the flag values passed by the user are invalid.
func (o *secretInitOpts) Validate() error {
if o.inputFilePath != "" && o.name != "" {
return errors.New("cannot specify `--cli-input-yaml` with `--name`")
}
if o.inputFilePath != "" && o.values != nil {
return errors.New("cannot specify `--cli-input-yaml` with `--values`")
}
if o.appName != "" {
_, err := o.store.GetApplication(o.appName)
if err != nil {
return fmt.Errorf("get application %s: %w", o.appName, err)
}
if o.values != nil {
for env := range o.values {
if _, err := o.targetEnv(env); err != nil {
return err
}
}
}
}
if o.name != "" {
if err := validateSecretName(o.name); err != nil {
return err
}
}
if o.inputFilePath != "" {
if _, err := o.fs.Stat(o.inputFilePath); err != nil {
return err
}
}
return nil
}
// Ask prompts the user for any required or important fields that are not provided.
func (o *secretInitOpts) Ask() error {
if o.overwrite {
log.Warningf("You have specified %s flag. Please note that overwriting an existing secret may break your deployed service.\n", color.HighlightCode(fmt.Sprintf("--%s", overwriteFlag)))
}
if o.inputFilePath != "" {
return nil
}
if err := o.askForAppName(); err != nil {
return err
}
if err := o.askForSecretName(); err != nil {
return err
}
if err := o.askForSecretValues(); err != nil {
return err
}
return nil
}
// Execute creates or updates the secrets.
func (o *secretInitOpts) Execute() error {
if o.inputFilePath != "" {
secrets, err := o.parseSecretsInputFile()
if err != nil {
return err
}
o.secretValues = secrets
if err := o.configureClientsAndUpgradeForEnvironments(secrets); err != nil {
return err
}
var errs []*errSecretFailedInSomeEnvironments
for secretName, secretValues := range secrets {
if err := o.putSecret(secretName, secretValues); err != nil {
errs = append(errs, err.(*errSecretFailedInSomeEnvironments))
}
log.Infoln("")
}
if len(errs) != 0 {
return &errBatchPutSecretsFailed{
errors: errs,
}
}
return nil
}
o.secretValues = map[string]map[string]string{
o.name: o.values,
}
if err := o.configureClientsAndUpgradeForEnvironments(o.secretValues); err != nil {
return err
}
return o.putSecret(o.name, o.values)
}
func (o *secretInitOpts) configureClientsAndUpgradeForEnvironments(secrets map[string]map[string]string) error {
envNames := make(map[string]struct{})
for _, values := range secrets {
for envName := range values {
envNames[envName] = struct{}{}
}
}
for envName := range envNames {
if err := o.configureClientsForEnv(envName); err != nil {
return err
}
if err := validateMinEnvVersion(o.ws, o.envCompatibilityChecker[envName], o.appName, envName, template.SecretInitMinEnvVersion, "secret init"); err != nil {
return err
}
}
return nil
}
func (o *secretInitOpts) putSecret(secretName string, values map[string]string) error {
envs := make([]string, 0)
for env := range values {
envs = append(envs, env)
}
if len(envs) == 0 {
return nil
}
log.Infof("...Put secret %s to environment %s\n", color.HighlightUserInput(secretName), english.WordSeries(envs, "and"))
errorsForEnvironments := make(map[string]error)
for envName, value := range values {
err := o.putSecretInEnv(secretName, envName, value)
if err != nil {
errorsForEnvironments[envName] = err
continue
}
}
for envName := range errorsForEnvironments {
log.Errorf("Failed to put secret %s in environment %s. See error message below.\n", color.HighlightUserInput(secretName), color.HighlightUserInput(envName))
}
if len(errorsForEnvironments) != 0 {
return &errSecretFailedInSomeEnvironments{
secretName: secretName,
errorsForEnvironments: errorsForEnvironments,
}
}
return nil
}
func (o *secretInitOpts) putSecretInEnv(secretName, envName, value string) error {
name := fmt.Sprintf(fmtSecretParameterName, o.appName, envName, secretName)
in := ssm.PutSecretInput{
Name: name,
Value: value,
Overwrite: o.overwrite,
Tags: map[string]string{
deploy.AppTagKey: o.appName,
deploy.EnvTagKey: envName,
},
}
out, err := o.secretPutters[envName].PutSecret(in)
if err != nil {
var targetErr *ssm.ErrParameterAlreadyExists
if errors.As(err, &targetErr) {
o.shouldShowOverwriteHint = true
log.Successf("Secret %s already exists in environment %s as %s. Did not overwrite. \n", color.HighlightUserInput(secretName), color.HighlightUserInput(envName), color.HighlightResource(name))
return nil
}
return err
}
version := aws.Int64Value(out.Version)
if version != 1 {
log.Successln(fmt.Sprintf("Secret %s already exists in environment %s. Overwritten.", name, color.HighlightUserInput(envName)))
return nil
}
log.Successln(fmt.Sprintf("Successfully put secret %s in environment %s as %s.", color.HighlightUserInput(secretName), color.HighlightUserInput(envName), color.HighlightResource(name)))
return nil
}
func (o *secretInitOpts) parseSecretsInputFile() (map[string]map[string]string, error) {
raw, err := o.readFile()
if err != nil {
return nil, err
}
type inputFile struct {
Secrets map[string]map[string]string `yaml:",inline"`
}
var f inputFile
if err := yaml.Unmarshal(raw, &f); err != nil {
return nil, fmt.Errorf("unmarshal input file: %w", err)
}
return f.Secrets, nil
}
func (o *secretInitOpts) askForAppName() error {
if o.appName != "" {
return nil
}
app, err := o.selector.Application(secretInitAppPrompt, secretInitAppPromptHelp)
if err != nil {
return fmt.Errorf("ask for an application to add the secret to: %w", err)
}
o.appName = app
return nil
}
func (o *secretInitOpts) askForSecretName() error {
if o.name != "" {
return nil
}
name, err := o.prompter.Get(secretInitSecretNamePrompt,
secretInitSecretNamePromptHelp,
validateSecretName,
prompt.WithFinalMessage("Secret name: "))
if err != nil {
return fmt.Errorf("ask for the secret name: %w", err)
}
o.name = name
return nil
}
func (o *secretInitOpts) askForSecretValues() error {
if o.values != nil {
return nil
}
envs, err := o.store.ListEnvironments(o.appName)
if err != nil {
return fmt.Errorf("list environments in app %s: %w", o.appName, err)
}
if len(envs) == 0 {
log.Errorf("Secrets are environment-level resources. Please run %s before running %s.\n",
color.HighlightCode("copilot env init"),
color.HighlightCode("copilot secret init"))
return fmt.Errorf("no environment is found in app %s", o.appName)
}
values := make(map[string]string)
for _, env := range envs {
value, err := o.prompter.GetSecret(
fmt.Sprintf(fmtSecretInitSecretValuePrompt, color.HighlightUserInput(o.name), env.Name),
fmt.Sprintf(fmtSecretInitSecretValuePromptHelp, color.HighlightUserInput(o.name), env.Name),
prompt.WithFinalMessage(fmt.Sprintf("%s secret value:", cases.Title(language.English).String(env.Name))),
)
if err != nil {
return fmt.Errorf("get secret value for %s in environment %s: %w", color.HighlightUserInput(o.name), env.Name, err)
}
if value != "" {
values[env.Name] = value
}
}
o.values = values
return nil
}
// RecommendActions shows recommended actions to do after running `secret init`.
func (o *secretInitOpts) RecommendActions() error {
secretsManifestExample := "secrets:"
for secretName := range o.secretValues {
currSecret := fmt.Sprintf("%s: %s", secretName, fmt.Sprintf(fmtSecretParameterNameMftExample, secretName))
secretsManifestExample = fmt.Sprintf("%s\n%s", secretsManifestExample, fmt.Sprintf(" %s", currSecret))
}
log.Infoln("You can refer to these secrets from your manifest file by editing the `secrets` section.")
log.Infoln(color.HighlightCodeBlock(secretsManifestExample))
return nil
}
type errSecretFailedInSomeEnvironments struct {
secretName string
errorsForEnvironments map[string]error
}
type errBatchPutSecretsFailed struct {
errors []*errSecretFailedInSomeEnvironments
}
func (e *errSecretFailedInSomeEnvironments) Error() string {
// Sort failure messages by environment names.
var envs []string
for env := range e.errorsForEnvironments {
envs = append(envs, env)
}
sort.Strings(envs)
out := make([]string, 0)
for _, env := range envs {
out = append(out, fmt.Sprintf("put secret %s in environment %s: %s", e.secretName, env, e.errorsForEnvironments[env].Error()))
}
return strings.Join(out, "\n")
}
func (e *errSecretFailedInSomeEnvironments) name() string {
return e.secretName
}
func (e *errBatchPutSecretsFailed) Error() string {
out := []string{
"batch put secrets:",
}
sort.SliceStable(e.errors, func(i, j int) bool {
return e.errors[i].name() < e.errors[j].name()
})
for _, err := range e.errors {
out = append(out, err.Error())
}
return strings.Join(out, "\n")
}
func (o *secretInitOpts) targetEnv(envName string) (*config.Environment, error) {
env, err := o.store.GetEnvironment(o.appName, envName)
if err != nil {
return nil, fmt.Errorf("get environment %s in application %s: %w", envName, o.appName, err)
}
return env, nil
}
// buildSecretInitCmd build the command for creating a new secret or updating an existing one.
func buildSecretInitCmd() *cobra.Command {
vars := secretInitVars{}
cmd := &cobra.Command{
Use: "init",
Short: "Create or update secrets in SSM Parameter Store.",
Example: `
Create a secret with prompts.
/code $ copilot secret init
Create a secret named db-password in multiple environments.
/code $ copilot secret init --name db-password
Create secrets from input.yml. For the format of the YAML file, please see https://aws.github.io/copilot-cli/docs/commands/secret-init/.
/code $ copilot secret init --cli-input-yaml input.yml`,
RunE: runCmdE(func(cmd *cobra.Command, args []string) error {
opts, err := newSecretInitOpts(vars)
if err != nil {
return err
}
if err := opts.Validate(); err != nil {
return err
}
if err := opts.Ask(); err != nil {
return err
}
err = opts.Execute()
if opts.shouldShowOverwriteHint {
log.Warningf("If you want to overwrite an existing secret, use the %s flag.\n", color.HighlightCode(fmt.Sprintf("--%s", overwriteFlag)))
}
if err != nil {
return err
}
if err := opts.RecommendActions(); err != nil {
return err
}
return nil
}),
}
cmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)
cmd.Flags().StringVarP(&vars.name, nameFlag, nameFlagShort, "", secretNameFlagDescription)
cmd.Flags().StringToStringVar(&vars.values, valuesFlag, nil, secretValuesFlagDescription)
cmd.Flags().BoolVar(&vars.overwrite, overwriteFlag, false, secretOverwriteFlagDescription)
cmd.Flags().StringVar(&vars.inputFilePath, inputFilePathFlag, "", secretInputFilePathFlagDescription)
return cmd
}