-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathenv.go
More file actions
1778 lines (1554 loc) · 53.7 KB
/
env.go
File metadata and controls
1778 lines (1554 loc) · 53.7 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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/alpha"
"github.com/azure/azure-dev/cli/azd/pkg/azapi"
"github.com/azure/azure-dev/cli/azd/pkg/azureutil"
"github.com/azure/azure-dev/cli/azd/pkg/entraid"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/environment/azdcontext"
"github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning"
"github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning/bicep"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/keyvault"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/output/ux"
"github.com/azure/azure-dev/cli/azd/pkg/project"
"github.com/azure/azure-dev/cli/azd/pkg/prompt"
"github.com/joho/godotenv"
"github.com/sethvargo/go-retry"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func envActions(root *actions.ActionDescriptor) *actions.ActionDescriptor {
group := root.Add("env", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "env",
Short: "Manage environments (ex: default environment, environment variables).",
},
HelpOptions: actions.ActionHelpOptions{
Description: getCmdEnvHelpDescription,
},
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupManage,
},
})
group.Add("set", &actions.ActionDescriptorOptions{
Command: newEnvSetCmd(),
FlagsResolver: newEnvSetFlags,
ActionResolver: newEnvSetAction,
})
group.Add("set-secret", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "set-secret <name>",
Short: "Set a name as a reference to a Key Vault secret in the environment.",
Long: "You can either create a new Key Vault secret or select an existing one.\n" +
"The provided name is the key for the .env file which holds the secret reference to the Key Vault secret.",
},
FlagsResolver: newEnvSetSecretFlags,
ActionResolver: newEnvSetSecretAction,
})
group.Add("select", &actions.ActionDescriptorOptions{
Command: newEnvSelectCmd(),
ActionResolver: newEnvSelectAction,
})
group.Add("new", &actions.ActionDescriptorOptions{
Command: newEnvNewCmd(),
FlagsResolver: newEnvNewFlags,
ActionResolver: newEnvNewAction,
})
group.Add("remove", &actions.ActionDescriptorOptions{
Command: newEnvRemoveCmd(),
FlagsResolver: newEnvRemoveFlags,
ActionResolver: newEnvRemoveAction,
HelpOptions: actions.ActionHelpOptions{
Description: getCmdEnvRemoveHelpDescription,
},
})
group.Add("list", &actions.ActionDescriptorOptions{
Command: newEnvListCmd(),
ActionResolver: newEnvListAction,
OutputFormats: []output.Format{output.JsonFormat, output.TableFormat},
DefaultFormat: output.TableFormat,
})
group.Add("refresh", &actions.ActionDescriptorOptions{
Command: newEnvRefreshCmd(),
FlagsResolver: newEnvRefreshFlags,
ActionResolver: newEnvRefreshAction,
OutputFormats: []output.Format{output.JsonFormat, output.NoneFormat},
DefaultFormat: output.NoneFormat,
})
group.Add("get-values", &actions.ActionDescriptorOptions{
Command: newEnvGetValuesCmd(),
FlagsResolver: newEnvGetValuesFlags,
ActionResolver: newEnvGetValuesAction,
OutputFormats: []output.Format{output.JsonFormat, output.EnvVarsFormat},
DefaultFormat: output.EnvVarsFormat,
})
group.Add("get-value", &actions.ActionDescriptorOptions{
Command: newEnvGetValueCmd(),
FlagsResolver: newEnvGetValueFlags,
ActionResolver: newEnvGetValueAction,
})
// Add env config sub-command group
configGroup := group.Add("config", &actions.ActionDescriptorOptions{
Command: &cobra.Command{
Use: "config",
Short: "Manage environment configuration (ex: stored in .azure/<environment>/config.json).",
},
HelpOptions: actions.ActionHelpOptions{
Description: getCmdEnvConfigHelpDescription,
Footer: getCmdEnvConfigHelpFooter,
},
})
configGroup.Add("get", &actions.ActionDescriptorOptions{
Command: newEnvConfigGetCmd(),
FlagsResolver: newEnvConfigGetFlags,
ActionResolver: newEnvConfigGetAction,
OutputFormats: []output.Format{output.JsonFormat},
DefaultFormat: output.JsonFormat,
})
configGroup.Add("set", &actions.ActionDescriptorOptions{
Command: newEnvConfigSetCmd(),
FlagsResolver: newEnvConfigSetFlags,
ActionResolver: newEnvConfigSetAction,
})
configGroup.Add("unset", &actions.ActionDescriptorOptions{
Command: newEnvConfigUnsetCmd(),
FlagsResolver: newEnvConfigUnsetFlags,
ActionResolver: newEnvConfigUnsetAction,
})
return group
}
func newEnvSetFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *envSetFlags {
flags := &envSetFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
func newEnvSetCmd() *cobra.Command {
return &cobra.Command{
Use: "set [<key> <value>] | [<key>=<value> ...] | [--file <filepath>]",
Short: "Set one or more environment values.",
Long: "Set one or more environment values using key-value pairs or by loading from a .env formatted file.",
Args: cobra.ArbitraryArgs,
// Sample arguments used in tests
Annotations: map[string]string{
"azdtest.use": "set key value",
},
}
}
type envSetFlags struct {
internal.EnvFlag
global *internal.GlobalCommandOptions
file string
}
func (f *envSetFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
f.EnvFlag.Bind(local, global)
local.StringVar(&f.file, "file", "", "Path to .env formatted file to load environment values from.")
f.global = global
}
type envSetAction struct {
console input.Console
azdCtx *azdcontext.AzdContext
env *environment.Environment
envManager environment.Manager
flags *envSetFlags
args []string
}
func newEnvSetAction(
azdCtx *azdcontext.AzdContext,
env *environment.Environment,
envManager environment.Manager,
console input.Console,
flags *envSetFlags,
args []string,
) actions.Action {
return &envSetAction{
console: console,
azdCtx: azdCtx,
env: env,
envManager: envManager,
flags: flags,
args: args,
}
}
func (e *envSetAction) Run(ctx context.Context) (*actions.ActionResult, error) {
// To track case conflicts
dotEnv := e.env.Dotenv()
keyValues := make(map[string]string)
// Handle file input if specified
if e.flags.file != "" {
if len(e.args) > 0 {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf(
"cannot combine --file flag with key-value arguments: %w",
internal.ErrInvalidFlagCombination),
Suggestion: "Use either '--file <path>' or '<key> <value>' arguments, not both.",
}
}
filename := e.flags.file
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("failed to open file %s: %w", filename, err)
}
defer file.Close()
keyValues, err = godotenv.Parse(file)
if err != nil {
return nil, fmt.Errorf("failed to parse file %s: %w", filename, err)
}
} else if len(e.args) == 0 {
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrNoEnvValuesProvided,
Suggestion: "Provide values as 'azd env set <key> <value>'," +
" 'azd env set <key>=<value>', or 'azd env set --file <path>'.",
}
} else if len(e.args) == 2 && !strings.Contains(e.args[0], "=") {
// Handle single key-value pair format: azd env set key value
key := e.args[0]
value := e.args[1]
keyValues[key] = value
} else {
// Handle key=value format: azd env set key=value [key2=value2 ...]
for _, arg := range e.args {
key, value, err := parseKeyValue(arg)
if err != nil {
return nil, err
}
keyValues[key] = value
}
}
// No environment values to set
if len(keyValues) == 0 {
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrNoEnvValuesProvided,
Suggestion: "Provide values as 'azd env set <key> <value>'," +
" 'azd env set <key>=<value>', or 'azd env set --file <path>'.",
}
}
// Apply the values
for key, value := range keyValues {
warnKeyCaseConflicts(ctx, e.console, dotEnv, key)
e.env.DotenvSet(key, value)
// Update to check case conflicts in subsequent keys
dotEnv[key] = value
}
if err := e.envManager.Save(ctx, e.env); err != nil {
return nil, fmt.Errorf("saving environment: %w", err)
}
return nil, nil
}
// parseKeyValue parses a key=value string and returns the key and value parts
func parseKeyValue(arg string) (string, string, error) {
parts := strings.SplitN(arg, "=", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid key=value format: %s", arg)
}
key := parts[0]
value := parts[1]
return key, value, nil
}
// Prints a warning message if there are any case-insensitive conflicts with the provided key
func warnKeyCaseConflicts(
ctx context.Context,
console input.Console,
dotEnv map[string]string,
key string) {
var conflicts []string
for k := range dotEnv {
if strings.EqualFold(k, key) && k != key {
conflicts = append(conflicts, "'"+k+"'")
}
}
if len(conflicts) == 1 {
console.MessageUxItem(ctx,
&ux.WarningMessage{
Description: fmt.Sprintf(
"'%s' already exists as %s. Did you mean to set %s instead?",
key,
conflicts[0],
conflicts[0]),
})
} else if len(conflicts) > 1 {
slices.Sort(conflicts)
console.MessageUxItem(ctx,
&ux.WarningMessage{
Description: fmt.Sprintf(
"'%s' already exists as %s",
key,
ux.ListAsText(conflicts)),
})
}
}
func newEnvSetSecretFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *envSetSecretFlags {
flags := &envSetSecretFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
type envSetSecretFlags struct {
internal.EnvFlag
global *internal.GlobalCommandOptions
}
func (f *envSetSecretFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
f.EnvFlag.Bind(local, global)
f.global = global
}
type envSetSecretAction struct {
console input.Console
azdCtx *azdcontext.AzdContext
env *environment.Environment
envManager environment.Manager
flags *envSetFlags
args []string
prompter prompt.Prompter
kvService keyvault.KeyVaultService
entraIdService entraid.EntraIdService
subResolver account.SubscriptionTenantResolver
userProfileService *azapi.UserProfileService
alphaFeatureManager *alpha.FeatureManager
projectConfig *project.ProjectConfig
}
func (e *envSetSecretAction) Run(ctx context.Context) (*actions.ActionResult, error) {
if len(e.args) < 1 {
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrNoArgsProvided,
Suggestion: "Run 'azd env set-secret <name>' specifying the secret name.",
}
}
secretName := e.args[0]
// When no interactive is supported in the terminal azd will not add numbers to the list when
// asking to select options. For example, instead of showing "1. Option 1", it will show "Option 1". This is useful
// when the user wants to prefill the selection in stdin before calling azd env set-secret (e.g. in a script).
listWithoutNumbers := !e.console.IsSpinnerInteractive()
createNewStrategy := "Create a new Key Vault secret"
selectExistingStrategy := "Select an existing Key Vault secret"
setSecretStrategies := []string{createNewStrategy, selectExistingStrategy}
selectedStrategyIndex, err := e.console.Select(
ctx,
input.ConsoleOptions{
Message: "Select how you want to set " + secretName,
Options: setSecretStrategies,
DefaultValue: createNewStrategy,
Help: "When creating a new Key Vault secret, you can either create a new Key Vault or" +
" pick an existing one. A Key Vault secret belongs to a Key Vault.",
})
if err != nil {
return nil, fmt.Errorf("selecting secret setting strategy: %w", err)
}
willCreateNewSecret := setSecretStrategies[selectedStrategyIndex] == createNewStrategy
createSuccessResult := func(secretName, kvSecretName, kvName string) *actions.ActionResult {
return &actions.ActionResult{
Message: &actions.ResultMessage{
Header: fmt.Sprintf("The key %s was saved in the environment as a reference to the"+
" Key Vault secret %s from the Key Vault %s",
output.WithBackticks(secretName),
output.WithBackticks(kvSecretName),
output.WithBackticks(kvName)),
FollowUp: fmt.Sprintf("Learn how to use Key Vault secrets with azd and more: %s",
output.WithLinkFormat("https://aka.ms/azd-env-set-secret")),
},
}
}
// Provide shortcuts for using the Key Vault created by composability (azd add)
if kvId, hasComposeKv := e.env.LookupEnv("AZURE_RESOURCE_VAULT_ID"); hasComposeKv { // KV is provisioned
resId, err := arm.ParseResourceID(kvId)
if err != nil {
return nil, fmt.Errorf("parsing key vault resource id: %w", err)
}
kvName := resId.Name
kvSubId := resId.SubscriptionID
subscriptionOptions := []string{"Yes", "No, use different key vault"}
useProjectKvPrompt, err := e.console.Select(
ctx,
input.ConsoleOptions{
Message: "Key vault detected in this project. Use this key vault?",
Options: subscriptionOptions,
DefaultValue: subscriptionOptions[0],
})
if err != nil {
return nil, fmt.Errorf("selecting key vault option: %w", err)
}
if useProjectKvPrompt == 0 { // Use project Key Vault
kvAccount := keyvault.Vault{
Name: kvName,
Id: kvId,
}
var kvSecretName string
if willCreateNewSecret {
kvSecretName, err = e.createNewKeyVaultSecret(ctx, secretName, kvSubId, kvAccount.Name)
} else {
kvSecretName, err = e.selectKeyVaultSecret(ctx, kvSubId, kvAccount.Name)
}
if err != nil {
return nil, err
}
envValue := keyvault.NewAzureKeyVaultSecret(kvSubId, kvAccount.Name, kvSecretName)
e.env.DotenvSet(secretName, envValue)
if err := e.envManager.Save(ctx, e.env); err != nil {
return nil, fmt.Errorf("saving environment: %w", err)
}
return createSuccessResult(secretName, kvSecretName, kvAccount.Name), nil
}
} else if _, hasProjectKv := e.projectConfig.Resources["vault"]; hasProjectKv { // KV defined but not provisioned yet
e.console.Message(ctx,
output.WithWarningFormat("\nAn existing project key vault is defined but is not provisioned yet. ")+
fmt.Sprintf("Run '%s' first to use it.\n", output.WithHighLightFormat("azd provision")))
options := []string{"Use a different key vault", "Cancel"}
useProjectKvPrompt, err := e.console.Select(
ctx,
input.ConsoleOptions{
Message: "How do you want to proceed?",
Options: options,
DefaultValue: options[0],
})
if err != nil {
return nil, fmt.Errorf("selecting key vault option: %w", err)
}
if useProjectKvPrompt == 1 { // Cancel
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrOperationCancelled,
Suggestion: "Run 'azd provision' to provision the project Key Vault first.",
}
}
}
subscriptionNote := "\nYou can set the Key Vault secret from any Azure subscription where you have access to."
e.console.Message(ctx, subscriptionNote)
// default messages based on willCreateNewSecret == true
pickSubscription := "Select the subscription where you want to create the Key Vault secret"
pickKvAccount := "Select the Key Vault where you want to create the Key Vault secret"
if !willCreateNewSecret {
// reassign messages for selecting existing secret
pickSubscription = "Select the subscription where the Key Vault secret is"
pickKvAccount = "Select the Key Vault where the Key Vault secret is"
}
subId, err := e.prompter.PromptSubscription(ctx, pickSubscription)
if err != nil {
return nil, fmt.Errorf("prompting for subscription: %w", err)
}
tenantId, err := e.subResolver.LookupTenant(ctx, subId)
if err != nil {
return nil, fmt.Errorf("looking up tenant for subscription: %w", err)
}
e.console.ShowSpinner(ctx, "Finding Key Vaults from the selected subscription", input.Step)
vaultsList, err := e.kvService.ListSubscriptionVaults(ctx, subId)
if err != nil {
return nil, fmt.Errorf("getting the list of Key Vaults: %w", err)
}
// prompt for vault selection
e.console.StopSpinner(ctx, "", input.Step)
atLeastOneKvAccountExists := len(vaultsList) > 0
if !atLeastOneKvAccountExists && !willCreateNewSecret {
e.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: "No Azure Key Vaults were found in the selected subscription",
})
// update the flow to offer creating a new Key Vault
willCreateNewSecret = true
}
createNewKvAccountOption := "Create a new Key Vault"
selectKvAccountOptions := []string{}
// Create a combined list with "Create a new Key Vault" as the first option
if willCreateNewSecret {
if listWithoutNumbers {
selectKvAccountOptions = append(selectKvAccountOptions, createNewKvAccountOption)
} else {
selectKvAccountOptions = append(selectKvAccountOptions, fmt.Sprintf("%2d. %s", 1, createNewKvAccountOption))
}
}
// Add the existing vaults with adjusted numbering
for index, vault := range vaultsList {
if listWithoutNumbers {
selectKvAccountOptions = append(selectKvAccountOptions, vault.Name)
} else {
offset := 1
// Existing KVs start at #2 since #1 will be "Create a new Key Vault"
if willCreateNewSecret {
offset = 2
}
selectKvAccountOptions = append(selectKvAccountOptions, fmt.Sprintf("%2d. %s", index+offset, vault.Name))
}
}
kvAccountSelectionIndex, err := e.console.Select(ctx, input.ConsoleOptions{
Message: pickKvAccount,
Options: selectKvAccountOptions,
DefaultValue: selectKvAccountOptions[0],
})
if err != nil {
return nil, fmt.Errorf("selecting Key Vault: %w", err)
}
willCreateNewKvAccount := false
if willCreateNewSecret {
willCreateNewKvAccount = kvAccountSelectionIndex == 0
if !willCreateNewKvAccount {
// when willCreateNewSecret is true, we added a new option at the beginning of the list
// to recover the original kv account name
kvAccountSelectionIndex--
}
}
var kvAccount keyvault.Vault
if atLeastOneKvAccountExists {
kvAccount = vaultsList[kvAccountSelectionIndex]
}
if willCreateNewKvAccount {
location, err := e.prompter.PromptLocation(
ctx, subId, "Select the location to create the Key Vault", nil, nil)
if err != nil {
return nil, fmt.Errorf("prompting for Key Vault location: %w", err)
}
rg, err := e.prompter.PromptResourceGroupFrom(ctx, subId, location, prompt.PromptResourceGroupFromOptions{
DefaultName: "rg-for-my-key-vault",
NewResourceGroupHelp: "The name of the new resource group where the Key Vault will be created.",
})
if err != nil {
return nil, fmt.Errorf("prompting for resource group: %w", err)
}
kvAccountName := ""
for {
kvAccountNameInput, err := e.console.Prompt(ctx, input.ConsoleOptions{
Message: "Enter a name for the Key Vault",
Help: "The name must be unique within the subscription and must be between 3 and 24 characters long",
})
if err != nil {
return nil, fmt.Errorf("prompting for Key Vault name: %w", err)
}
if kvAccountNameInput == "" {
e.console.Message(ctx, "Key Vault name cannot be empty")
continue
}
kvAccountName = kvAccountNameInput
break
}
e.console.ShowSpinner(ctx, "Creating Key Vault", input.Step)
vault, err := e.kvService.CreateVault(ctx, tenantId, subId, rg, location, kvAccountName)
e.console.StopSpinner(ctx, "", input.Step)
if err != nil {
return nil, fmt.Errorf("error creating Key Vault: %w", err)
}
kvAccount = vault
// RBAC role assignment
e.console.ShowSpinner(ctx, "Adding Administrator Role", input.Step)
principalId, err := azureutil.GetCurrentPrincipalId(ctx, e.userProfileService, tenantId)
if err != nil {
return nil, fmt.Errorf("getting current principal ID: %w", err)
}
err = e.entraIdService.CreateRbac(
ctx, subId, kvAccount.Id, keyvault.RoleIdKeyVaultAdministrator, principalId)
if err != nil {
return nil, fmt.Errorf("adding Administrator Role: %w", err)
}
e.console.StopSpinner(ctx, "", input.Step)
}
var kvSecretName string
if willCreateNewSecret {
kvSecretName, err = e.createNewKeyVaultSecret(ctx, secretName, subId, kvAccount.Name)
} else {
kvSecretName, err = e.selectKeyVaultSecret(ctx, subId, kvAccount.Name)
}
if err != nil {
return nil, err
}
// akvs -> Azure Key Vault Secret (akvs://<subId>/<keyvault-name>/<secret-name>)
envValue := keyvault.NewAzureKeyVaultSecret(subId, kvAccount.Name, kvSecretName)
e.env.DotenvSet(secretName, envValue)
if err := e.envManager.Save(ctx, e.env); err != nil {
return nil, fmt.Errorf("saving environment: %w", err)
}
return createSuccessResult(secretName, kvSecretName, kvAccount.Name), nil
}
// createNewKeyVaultSecret creates a new secret in an Azure Key Vault and returns the name of the created secret.
func (e *envSetSecretAction) createNewKeyVaultSecret(ctx context.Context, secretName, subId, kvName string) (string, error) {
var kvSecretName string
var err error
for {
kvSecretName, err = e.console.Prompt(ctx, input.ConsoleOptions{
Message: "Enter a name for the Key Vault secret",
DefaultValue: strings.ReplaceAll(secretName, "_", "-") + "-kv-secret",
})
if err != nil {
return "", fmt.Errorf("prompting for Key Vault secret name: %w", err)
}
if keyvault.IsValidSecretName(kvSecretName) {
break
}
e.console.Message(ctx, "Invalid Key Vault secret name. The name must be between 1 and 127 characters"+
" long and can contain only alphanumeric characters and dashes.")
}
kvSecretValue, err := e.console.Prompt(ctx, input.ConsoleOptions{
Message: "Enter the value for the Key Vault secret",
IsPassword: true,
})
if err != nil {
return "", fmt.Errorf("prompting for secret value: %w", err)
}
// Creating a secret in a new account too soon can fail due to rbac role assignment not being ready
err = retry.Do(
ctx,
retry.WithMaxRetries(3, retry.NewConstant(5*time.Second)),
func(ctx context.Context) error {
err = e.kvService.CreateKeyVaultSecret(ctx, subId, kvName, kvSecretName, kvSecretValue)
if err != nil {
return retry.RetryableError(fmt.Errorf("creating Key Vault secret: %w", err))
}
return nil
},
)
if err != nil {
return "", fmt.Errorf("setting Key Vault secret: %w", err)
}
return kvSecretName, nil
}
// selectKeyVaultSecret presents a selection list of secrets from the specified Key Vault and
// returns the selected secret name.
func (e *envSetSecretAction) selectKeyVaultSecret(ctx context.Context, subId string, kvName string) (string, error) {
listWithoutNumbers := !e.console.IsSpinnerInteractive()
secretsInKv, err := e.kvService.ListKeyVaultSecrets(ctx, subId, kvName)
if err != nil {
return "", fmt.Errorf("listing Key Vault secrets: %w", err)
}
if len(secretsInKv) == 0 {
return "", fmt.Errorf("no Key Vault secrets were found in the selected Key Vault")
}
options := make([]string, len(secretsInKv))
for i, secret := range secretsInKv {
if listWithoutNumbers {
options[i] = secret
} else {
options[i] = fmt.Sprintf("%2d. %s", i+1, secret)
}
}
secretSelectionIndex, err := e.console.Select(ctx, input.ConsoleOptions{
Message: "Select the Key Vault secret",
Options: options,
DefaultValue: options[0],
})
if err != nil {
return "", fmt.Errorf("selecting Key Vault secret: %w", err)
}
return secretsInKv[secretSelectionIndex], nil
}
func newEnvSetSecretAction(
azdCtx *azdcontext.AzdContext,
env *environment.Environment,
envManager environment.Manager,
console input.Console,
flags *envSetFlags,
args []string,
prompter prompt.Prompter,
kvService keyvault.KeyVaultService,
entraIdService entraid.EntraIdService,
subResolver account.SubscriptionTenantResolver,
userProfileService *azapi.UserProfileService,
alphaFeatureManager *alpha.FeatureManager,
projectConfig *project.ProjectConfig,
) actions.Action {
return &envSetSecretAction{
console: console,
azdCtx: azdCtx,
env: env,
envManager: envManager,
flags: flags,
args: args,
prompter: prompter,
kvService: kvService,
entraIdService: entraIdService,
subResolver: subResolver,
userProfileService: userProfileService,
alphaFeatureManager: alphaFeatureManager,
projectConfig: projectConfig,
}
}
func newEnvSelectCmd() *cobra.Command {
return &cobra.Command{
Use: "select [<environment>]",
Short: "Set the default environment.",
Args: cobra.MaximumNArgs(1),
}
}
type envSelectAction struct {
azdCtx *azdcontext.AzdContext
envManager environment.Manager
console input.Console
args []string
}
func newEnvSelectAction(
azdCtx *azdcontext.AzdContext,
envManager environment.Manager,
console input.Console,
args []string,
) actions.Action {
return &envSelectAction{
azdCtx: azdCtx,
envManager: envManager,
console: console,
args: args,
}
}
func (e *envSelectAction) Run(ctx context.Context) (*actions.ActionResult, error) {
var environmentName string
// If no argument provided, prompt the user to select an environment
if len(e.args) == 0 {
envs, err := e.envManager.List(ctx)
if err != nil {
return nil, fmt.Errorf("listing environments: %w", err)
}
if len(envs) == 0 {
return nil, &internal.ErrorWithSuggestion{
Err: internal.ErrNoEnvironmentsFound,
Suggestion: "Run 'azd env new <environment-name>' to create an environment.",
}
}
// Build list of environment names
envNames := make([]string, len(envs))
for i, env := range envs {
envNames[i] = env.Name
}
selection, err := e.console.Select(ctx, input.ConsoleOptions{
Message: "Select an environment:",
Options: envNames,
})
if err != nil {
return nil, fmt.Errorf("selecting environment: %w", err)
}
environmentName = envNames[selection]
} else {
environmentName = e.args[0]
}
_, err := e.envManager.Get(ctx, environmentName)
if errors.Is(err, environment.ErrNotFound) {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf("environment '%s' does not exist: %w",
environmentName, environment.ErrNotFound),
Suggestion: fmt.Sprintf(
"Run 'azd env list' to see environments, or 'azd env new %s' to create it.", environmentName),
}
} else if err != nil {
return nil, fmt.Errorf("ensuring environment exists: %w", err)
}
if err := e.azdCtx.SetProjectState(azdcontext.ProjectState{DefaultEnvironment: environmentName}); err != nil {
return nil, fmt.Errorf("setting default environment: %w", err)
}
return nil, nil
}
func newEnvListCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List environments.",
Aliases: []string{"ls"},
}
}
type envListAction struct {
envManager environment.Manager
azdCtx *azdcontext.AzdContext
formatter output.Formatter
writer io.Writer
}
func newEnvListAction(
envManager environment.Manager,
azdCtx *azdcontext.AzdContext,
formatter output.Formatter,
writer io.Writer,
) actions.Action {
return &envListAction{
envManager: envManager,
azdCtx: azdCtx,
formatter: formatter,
writer: writer,
}
}
func (e *envListAction) Run(ctx context.Context) (*actions.ActionResult, error) {
envs, err := e.envManager.List(ctx)
if err != nil {
return nil, fmt.Errorf("listing environments: %w", err)
}
tracing.SetUsageAttributes(fields.EnvCountKey.Int(len(envs)))
if e.formatter.Kind() == output.TableFormat {
columns := []output.Column{
{
Heading: "NAME",
ValueTemplate: "{{.Name}}",
},
{
Heading: "DEFAULT",
ValueTemplate: "{{.IsDefault}}",
},
{
Heading: "LOCAL",
ValueTemplate: "{{.HasLocal}}",
},
{
Heading: "REMOTE",
ValueTemplate: "{{.HasRemote}}",
},
}
err = e.formatter.Format(envs, e.writer, output.TableFormatterOptions{
Columns: columns,
})
} else {
err = e.formatter.Format(envs, e.writer, nil)
}
if err != nil {
return nil, err
}
return nil, nil
}
type envNewFlags struct {
subscription string
location string
global *internal.GlobalCommandOptions
}
func (f *envNewFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
local.StringVar(
&f.subscription,
"subscription",
"",
"ID of an Azure subscription to use for the new environment",
)
local.StringVarP(&f.location, "location", "l", "", "Azure location for the new environment")
f.global = global
}
func newEnvNewFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *envNewFlags {
flags := &envNewFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
func newEnvNewCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "new <environment>",
Short: "Create a new environment and set it as the default.",
}
cmd.Args = cobra.MaximumNArgs(1)
return cmd
}
type envNewAction struct {
azdCtx *azdcontext.AzdContext
envManager environment.Manager
flags *envNewFlags
args []string
console input.Console
}
func newEnvNewAction(
azdCtx *azdcontext.AzdContext,
envManager environment.Manager,
flags *envNewFlags,
args []string,
console input.Console,
) actions.Action {
return &envNewAction{
azdCtx: azdCtx,
envManager: envManager,
flags: flags,
args: args,
console: console,
}
}
func (en *envNewAction) Run(ctx context.Context) (*actions.ActionResult, error) {
environmentName := ""
if len(en.args) >= 1 {
environmentName = en.args[0]
}
envSpec := environment.Spec{
Name: environmentName,
Subscription: en.flags.subscription,
Location: en.flags.location,
}
env, err := en.envManager.Create(ctx, envSpec)
if err != nil {
return nil, fmt.Errorf("creating new environment: %w", err)
}
envs, err := en.envManager.List(ctx)
if err != nil {
return nil, fmt.Errorf("listing environments: %w", err)
}
if len(envs) == 1 {
// If this is the only environment, set it as the default environment
if err := en.azdCtx.SetProjectState(azdcontext.ProjectState{DefaultEnvironment: env.Name()}); err != nil {
return nil, fmt.Errorf("saving default environment: %w", err)
}
en.console.Message(ctx,