/
bicep_provider.go
1704 lines (1473 loc) · 53.1 KB
/
bicep_provider.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
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 bicep
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"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/azure"
"github.com/azure/azure-dev/cli/azd/pkg/cmdsubst"
"github.com/azure/azure-dev/cli/azd/pkg/convert"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/infra"
. "github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"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/prompt"
"github.com/azure/azure-dev/cli/azd/pkg/tools"
"github.com/azure/azure-dev/cli/azd/pkg/tools/azcli"
"github.com/azure/azure-dev/cli/azd/pkg/tools/bicep"
"github.com/benbjohnson/clock"
"github.com/drone/envsubst"
"golang.org/x/exp/maps"
)
const DefaultModule = "main"
type bicepDeploymentDetails struct {
// Template is the template to deploy during the deployment operation.
Template azure.RawArmTemplate
// Parameters are the values to provide to the template during the deployment operation.
Parameters azure.ArmParameters
// TemplateOutputs are the outputs as specified by the template.
TemplateOutputs azure.ArmTemplateOutputs
// Target is the unique resource in azure that represents the deployment that will happen. A target can be scoped to
// either subscriptions, or resource groups.
Target infra.Deployment
}
// BicepProvider exposes infrastructure provisioning using Azure Bicep templates
type BicepProvider struct {
env *environment.Environment
projectPath string
options Options
console input.Console
bicepCli bicep.BicepCli
azCli azcli.AzCli
deploymentsService azapi.Deployments
deploymentOperations azapi.DeploymentOperations
prompters prompt.Prompter
curPrincipal CurrentPrincipalIdProvider
alphaFeatureManager *alpha.FeatureManager
clock clock.Clock
}
var ErrResourceGroupScopeNotSupported = fmt.Errorf(
"resource group scoped deployments are currently under alpha support and need to be explicitly enabled."+
" Run `%s` to enable this feature.", alpha.GetEnableCommand(ResourceGroupDeploymentFeature),
)
// Name gets the name of the infra provider
func (p *BicepProvider) Name() string {
return "Bicep"
}
func (p *BicepProvider) RequiredExternalTools() []tools.ExternalTool {
return []tools.ExternalTool{}
}
func (p *BicepProvider) Initialize(ctx context.Context, projectPath string, options Options) error {
if strings.TrimSpace(options.Module) == "" {
options.Module = DefaultModule
}
p.projectPath = projectPath
p.options = options
requiredTools := p.RequiredExternalTools()
if err := tools.EnsureInstalled(ctx, requiredTools...); err != nil {
return err
}
return p.EnsureEnv(ctx)
}
// EnsureEnv ensures that the environment is in a provision-ready state with required values set, prompting the user if
// values are unset.
//
// An environment is considered to be in a provision-ready state if it contains both an AZURE_SUBSCRIPTION_ID and
// AZURE_LOCATION value. Additionally, for resource group scoped deployments, an AZURE_RESOURCE_GROUP value is required.
func (p *BicepProvider) EnsureEnv(ctx context.Context) error {
if err := EnsureSubscriptionAndLocation(ctx, p.env, p.prompters); err != nil {
return err
}
modulePath := p.modulePath()
if _, err := os.Stat(modulePath); errors.Is(err, os.ErrNotExist) {
// If there's not template, just behave as if we are in a subscription scope (and don't ask about
// AZURE_RESOURCE_GROUP). Future operations which try to use the infrastructure may fail, but that's ok. These
// failures will have reasonable error messages.
//
// We want to handle the case where the provider can `Initialize` even without a template, because we do this
// in a few of our end to end telemetry tests to speed things up.
return nil
}
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return fmt.Errorf("compiling bicep template: %w", err)
}
scope, err := compileResult.Template.TargetScope()
if err != nil {
return err
}
if scope == azure.DeploymentScopeResourceGroup {
if !p.alphaFeatureManager.IsEnabled(ResourceGroupDeploymentFeature) {
return ErrResourceGroupScopeNotSupported
}
p.console.WarnForFeature(ctx, ResourceGroupDeploymentFeature)
if p.env.Getenv(environment.ResourceGroupEnvVarName) == "" {
rgName, err := p.prompters.PromptResourceGroup(ctx)
if err != nil {
return err
}
p.env.DotenvSet(environment.ResourceGroupEnvVarName, rgName)
if err := p.env.Save(); err != nil {
return fmt.Errorf("saving resource group name: %w", err)
}
}
}
return nil
}
func (p *BicepProvider) State(ctx context.Context, options *StateOptions) (*StateResult, error) {
if options == nil {
options = &StateOptions{}
}
var err error
spinnerMessage := "Loading Bicep template"
// TODO: Report progress, "Loading Bicep template"
p.console.ShowSpinner(ctx, spinnerMessage, input.Step)
defer func() {
// Make sure we stop the spinner if an error occurs with the last message.
if err != nil {
p.console.StopSpinner(ctx, spinnerMessage, input.StepFailed)
}
}()
var scope infra.Scope
var outputs azure.ArmTemplateOutputs
var scopeErr error
modulePath := p.modulePath()
if _, err := os.Stat(modulePath); err == nil {
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, fmt.Errorf("compiling bicep template: %w", err)
}
scope, err = p.scopeForTemplate(ctx, compileResult.Template)
if err != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
outputs = compileResult.Template.Outputs
} else if errors.Is(err, os.ErrNotExist) {
// To support BYOI (bring your own infrastructure)
// We need to support the case where there template does not contain an `infra` folder.
scope, scopeErr = p.inferScopeFromEnv(ctx)
if scopeErr != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
outputs = azure.ArmTemplateOutputs{}
}
// TODO: Report progress, "Retrieving Azure deployment"
spinnerMessage = "Retrieving Azure deployment"
p.console.ShowSpinner(ctx, spinnerMessage, input.Step)
var deployment *armresources.DeploymentExtended
deployments, err := p.findCompletedDeployments(ctx, p.env.GetEnvName(), scope, options.Hint())
p.console.StopSpinner(ctx, "", input.StepDone)
if err != nil {
p.console.StopSpinner(ctx, spinnerMessage, input.StepFailed)
return nil, fmt.Errorf("retrieving deployment: %w", err)
} else {
p.console.StopSpinner(ctx, "", input.StepDone)
}
if len(deployments) > 1 {
deploymentOptions := getDeploymentOptions(ctx, deployments)
p.console.Message(ctx, output.WithWarningFormat("WARNING: Multiple matching deployments were found\n"))
promptConfig := input.ConsoleOptions{
Message: "Select a deployment to continue:",
Options: deploymentOptions,
}
selectedDeployment, err := p.console.Select(ctx, promptConfig)
if err != nil {
return nil, err
}
deployment = deployments[selectedDeployment]
p.console.Message(ctx, "")
} else {
deployment = deployments[0]
}
azdDeployment, err := p.createDeploymentFromArmDeployment(scope, *deployment.Name)
if err != nil {
return nil, err
}
p.console.MessageUxItem(ctx, &ux.DoneMessage{
Message: fmt.Sprintf("Retrieving Azure deployment (%s)", output.WithHighLightFormat(*deployment.Name)),
})
state := State{}
state.Resources = make([]Resource, len(deployment.Properties.OutputResources))
for idx, res := range deployment.Properties.OutputResources {
state.Resources[idx] = Resource{
Id: *res.ID,
}
}
state.Outputs = p.createOutputParameters(
outputs,
azapi.CreateDeploymentOutput(deployment.Properties.Outputs),
)
p.console.MessageUxItem(ctx, &ux.DoneMessage{
Message: fmt.Sprintf("Updated %d environment variables", len(state.Outputs)),
})
p.console.Message(ctx, fmt.Sprintf(
"\nPopulated environment from Azure infrastructure deployment: %s",
output.WithHyperlink(azdDeployment.OutputsUrl(), *deployment.Name),
))
return &StateResult{
State: &state,
}, nil
}
func (p *BicepProvider) createDeploymentFromArmDeployment(
scope infra.Scope,
deploymentName string,
) (infra.Deployment, error) {
switch scope.(type) {
case *infra.ResourceGroupScope:
return infra.NewResourceGroupDeployment(
p.deploymentsService,
p.deploymentOperations,
p.env.GetSubscriptionId(),
p.env.Getenv(environment.ResourceGroupEnvVarName),
deploymentName,
), nil
case *infra.SubscriptionScope:
return infra.NewSubscriptionDeployment(
p.deploymentsService,
p.deploymentOperations,
p.env.GetLocation(),
p.env.GetSubscriptionId(),
deploymentName,
), nil
default:
return nil, errors.New("unsupported deployment scope")
}
}
var ResourceGroupDeploymentFeature = alpha.MustFeatureKey("resourceGroupDeployments")
const bicepFileExtension = ".bicep"
const bicepparamFileExtension = ".bicepparam"
func isBicepFile(modulePath string) bool {
return filepath.Ext(modulePath) == bicepFileExtension
}
func isBicepParamFile(modulePath string) bool {
return filepath.Ext(modulePath) == bicepparamFileExtension
}
// Plans the infrastructure provisioning
func (p *BicepProvider) plan(ctx context.Context) (*Deployment, *bicepDeploymentDetails, error) {
p.console.ShowSpinner(ctx, "Creating a deployment plan", input.Step)
modulePath := p.modulePath()
// TODO: Report progress, "Compiling Bicep template"
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, nil, fmt.Errorf("creating template: %w", err)
}
// for .bicepparam, parameters are resolved as part of bicep compilation
armParameters := compileResult.Parameters
// for .bicep, azd must load a parameters.json file and create the ArmParameters
if isBicepFile(modulePath) {
parameters, err := p.loadParameters(ctx)
if err != nil {
return nil, nil, fmt.Errorf("resolving bicep parameters file: %w", err)
}
configuredParameters, err := p.ensureParameters(ctx, compileResult.Template, parameters)
if err != nil {
return nil, nil, err
}
armParameters = configuredParameters
}
deployment, err := p.convertToDeployment(compileResult.Template)
if err != nil {
return nil, nil, err
}
deploymentScope, err := compileResult.Template.TargetScope()
if err != nil {
return nil, nil, err
}
var target infra.Deployment
if deploymentScope == azure.DeploymentScopeSubscription {
target = infra.NewSubscriptionDeployment(
p.deploymentsService,
p.deploymentOperations,
p.env.GetLocation(),
p.env.GetSubscriptionId(),
deploymentNameForEnv(p.env.GetEnvName(), p.clock),
)
} else if deploymentScope == azure.DeploymentScopeResourceGroup {
target = infra.NewResourceGroupDeployment(
p.deploymentsService,
p.deploymentOperations,
p.env.GetSubscriptionId(),
p.env.Getenv(environment.ResourceGroupEnvVarName),
deploymentNameForEnv(p.env.GetEnvName(), p.clock),
)
} else {
return nil, nil, fmt.Errorf("unsupported scope: %s", deploymentScope)
}
return deployment, &bicepDeploymentDetails{
Template: compileResult.RawArmTemplate,
TemplateOutputs: compileResult.Template.Outputs,
Parameters: armParameters,
Target: target,
}, nil
}
// cArmDeploymentNameLengthMax is the maximum length of the name of a deployment in ARM.
const cArmDeploymentNameLengthMax = 64
// deploymentNameForEnv creates a name to use for the deployment object for a given environment. It appends the current
// unix time to the environment name (separated by a hyphen) to provide a unique name for each deployment. If the resulting
// name is longer than the ARM limit, the longest suffix of the name under the limit is returned.
func deploymentNameForEnv(envName string, clock clock.Clock) string {
name := fmt.Sprintf("%s-%d", envName, clock.Now().Unix())
if len(name) <= cArmDeploymentNameLengthMax {
return name
}
return name[len(name)-cArmDeploymentNameLengthMax:]
}
// Provisioning the infrastructure within the specified template
func (p *BicepProvider) Deploy(ctx context.Context) (*DeployResult, error) {
deployment, bicepDeploymentData, err := p.plan(ctx)
if err != nil {
return nil, err
}
cancelProgress := make(chan bool)
defer func() { cancelProgress <- true }()
go func() {
// Disable reporting progress if needed
if use, err := strconv.ParseBool(os.Getenv("AZD_DEBUG_PROVISION_PROGRESS_DISABLE")); err == nil && use {
log.Println("Disabling progress reporting since AZD_DEBUG_PROVISION_PROGRESS_DISABLE was set")
<-cancelProgress
return
}
// Report incremental progress
resourceManager := infra.NewAzureResourceManager(p.azCli, p.deploymentOperations)
progressDisplay := NewProvisioningProgressDisplay(resourceManager, p.console, bicepDeploymentData.Target)
// Make initial delay shorter to be more responsive in displaying initial progress
initialDelay := 3 * time.Second
regularDelay := 10 * time.Second
timer := time.NewTimer(initialDelay)
queryStartTime := time.Now()
for {
select {
case <-cancelProgress:
timer.Stop()
return
case <-timer.C:
if err := progressDisplay.ReportProgress(ctx, &queryStartTime); err != nil {
// We don't want to fail the whole deployment if a progress reporting error occurs
log.Printf("error while reporting progress: %s", err.Error())
}
timer.Reset(regularDelay)
}
}
}()
// Start the deployment
p.console.ShowSpinner(ctx, "Creating/Updating resources", input.Step)
deployResult, err := p.deployModule(
ctx,
bicepDeploymentData.Target,
bicepDeploymentData.Template,
bicepDeploymentData.Parameters,
map[string]*string{
azure.TagKeyAzdEnvName: to.Ptr(p.env.GetEnvName()),
},
)
if err != nil {
return nil, err
}
deployment.Outputs = p.createOutputParameters(
bicepDeploymentData.TemplateOutputs,
azapi.CreateDeploymentOutput(deployResult.Properties.Outputs),
)
return &DeployResult{
Deployment: deployment,
}, nil
}
// Preview runs deploy using the what-if argument
func (p *BicepProvider) Preview(ctx context.Context) (*DeployPreviewResult, error) {
_, bicepDeploymentData, err := p.plan(ctx)
if err != nil {
return nil, err
}
p.console.ShowSpinner(ctx, "Generating infrastructure preview", input.Step)
targetScope := bicepDeploymentData.Target
deployPreviewResult, err := targetScope.DeployPreview(
ctx,
bicepDeploymentData.Template,
bicepDeploymentData.Parameters,
)
if err != nil {
return nil, err
}
if deployPreviewResult.Error != nil {
deploymentErr := *deployPreviewResult.Error
errDetailsList := make([]string, len(deploymentErr.Details))
for index, errDetail := range deploymentErr.Details {
errDetailsList[index] = fmt.Sprintf(
"code: %s, message: %s",
convert.ToValueWithDefault(errDetail.Code, ""),
convert.ToValueWithDefault(errDetail.Message, ""),
)
}
var errDetails string
if len(errDetailsList) > 0 {
errDetails = fmt.Sprintf(" Details: %s", strings.Join(errDetailsList, "\n"))
}
return nil, fmt.Errorf(
"generating preview: error code: %s, message: %s.%s",
convert.ToValueWithDefault(deploymentErr.Code, ""),
convert.ToValueWithDefault(deploymentErr.Message, ""),
errDetails,
)
}
var changes []*DeploymentPreviewChange
for _, change := range deployPreviewResult.Properties.Changes {
resourceAfter := change.After.(map[string]interface{})
changes = append(changes, &DeploymentPreviewChange{
ChangeType: ChangeType(*change.ChangeType),
ResourceId: Resource{
Id: *change.ResourceID,
},
ResourceType: resourceAfter["type"].(string),
Name: resourceAfter["name"].(string),
})
}
return &DeployPreviewResult{
Preview: &DeploymentPreview{
Status: *deployPreviewResult.Status,
Properties: &DeploymentPreviewProperties{
Changes: changes,
},
},
}, nil
}
type itemToPurge struct {
resourceType string
count int
purge func(skipPurge bool, self *itemToPurge) error
cognitiveAccounts []cognitiveAccount
}
func (p *BicepProvider) scopeForTemplate(ctx context.Context, t azure.ArmTemplate) (infra.Scope, error) {
deploymentScope, err := t.TargetScope()
if err != nil {
return nil, err
}
if deploymentScope == azure.DeploymentScopeSubscription {
return infra.NewSubscriptionScope(
p.deploymentsService, p.deploymentOperations, p.env.GetSubscriptionId()), nil
} else if deploymentScope == azure.DeploymentScopeResourceGroup {
return infra.NewResourceGroupScope(
p.deploymentsService,
p.deploymentOperations,
p.env.GetSubscriptionId(),
p.env.Getenv(environment.ResourceGroupEnvVarName),
), nil
} else {
return nil, fmt.Errorf("unsupported deployment scope: %s", deploymentScope)
}
}
func (p *BicepProvider) inferScopeFromEnv(ctx context.Context) (infra.Scope, error) {
if resourceGroup, has := p.env.LookupEnv(environment.ResourceGroupEnvVarName); has {
return infra.NewResourceGroupScope(
p.deploymentsService,
p.deploymentOperations,
p.env.GetSubscriptionId(),
resourceGroup,
), nil
} else {
return infra.NewSubscriptionScope(
p.deploymentsService,
p.deploymentOperations,
p.env.GetSubscriptionId(),
), nil
}
}
// Destroys the specified deployment by deleting all azure resources, resource groups & deployments that are referenced.
func (p *BicepProvider) Destroy(ctx context.Context, options DestroyOptions) (*DestroyResult, error) {
modulePath := p.modulePath()
// TODO: Report progress, "Compiling Bicep template"
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, fmt.Errorf("creating template: %w", err)
}
scope, err := p.scopeForTemplate(ctx, compileResult.Template)
if err != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
// TODO: Report progress, "Fetching resource groups"
deployments, err := p.findCompletedDeployments(ctx, p.env.GetEnvName(), scope, "")
if err != nil {
return nil, err
}
rgsFromDeployment := resourceGroupsToDelete(deployments[0])
// TODO: Report progress, "Fetching resources"
groupedResources, err := p.getAllResourcesToDelete(ctx, rgsFromDeployment)
if err != nil {
return nil, fmt.Errorf("getting resources to delete: %w", err)
}
allResources := []azcli.AzCliResource{}
for _, groupResources := range groupedResources {
allResources = append(allResources, groupResources...)
}
// TODO: Report progress, "Getting Key Vaults to purge"
keyVaults, err := p.getKeyVaultsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting key vaults to purge: %w", err)
}
// TODO: Report progress, "Getting Managed HSMs to purge"
managedHSMs, err := p.getManagedHSMsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting managed hsms to purge: %w", err)
}
// TODO: Report progress, "Getting App Configurations to purge"
appConfigs, err := p.getAppConfigsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting app configurations to purge: %w", err)
}
// TODO: Report progress, "Getting API Management Services to purge"
apiManagements, err := p.getApiManagementsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting API managements to purge: %w", err)
}
// TODO: Report progress, "Getting Cognitive Accounts to purge"
cognitiveAccounts, err := p.getCognitiveAccountsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting cognitive accounts to purge: %w", err)
}
if err := p.destroyResourceGroups(ctx, options, groupedResources, len(allResources)); err != nil {
return nil, fmt.Errorf("deleting resource groups: %w", err)
}
keyVaultsPurge := itemToPurge{
resourceType: "Key Vault",
count: len(keyVaults),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeKeyVaults(ctx, keyVaults, options, skipPurge)
},
}
managedHSMsPurge := itemToPurge{
resourceType: "Managed HSM",
count: len(managedHSMs),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeManagedHSMs(ctx, managedHSMs, options, skipPurge)
},
}
appConfigsPurge := itemToPurge{
resourceType: "App Configuration",
count: len(appConfigs),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeAppConfigs(ctx, appConfigs, options, skipPurge)
},
}
aPIManagement := itemToPurge{
resourceType: "API Management",
count: len(apiManagements),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeAPIManagement(ctx, apiManagements, options, skipPurge)
},
}
var purgeItem []itemToPurge
for _, item := range []itemToPurge{keyVaultsPurge, managedHSMsPurge, appConfigsPurge, aPIManagement} {
if item.count > 0 {
purgeItem = append(purgeItem, item)
}
}
// cognitive services are grouped by resource group because the name of the resource group is required to purge
groupByKind := cognitiveAccountsByKind(cognitiveAccounts)
for name, cogAccounts := range groupByKind {
addPurgeItem := itemToPurge{
resourceType: name,
count: len(cogAccounts),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeCognitiveAccounts(ctx, self.cognitiveAccounts, options, skipPurge)
},
cognitiveAccounts: groupByKind[name],
}
purgeItem = append(purgeItem, addPurgeItem)
}
if err := p.purgeItems(ctx, purgeItem, options); err != nil {
return nil, fmt.Errorf("purging resources: %w", err)
}
destroyResult := &DestroyResult{
InvalidatedEnvKeys: maps.Keys(p.createOutputParameters(
compileResult.Template.Outputs,
azapi.CreateDeploymentOutput(deployments[0].Properties.Outputs),
)),
}
// Since we have deleted the resource group, add AZURE_RESOURCE_GROUP to the list of invalidated env vars
// so it will be removed from the .env file.
if _, ok := scope.(*infra.ResourceGroupScope); ok {
destroyResult.InvalidatedEnvKeys = append(
destroyResult.InvalidatedEnvKeys, environment.ResourceGroupEnvVarName,
)
}
return destroyResult, nil
}
// A local type for adding the resource group to a cognitive account as it is required for purging
type cognitiveAccount struct {
account armcognitiveservices.Account
resourceGroup string
}
// transform a map of resourceGroup and accounts to group by kind in all resource groups but keeping the resource group
// on each account
func cognitiveAccountsByKind(
accountsByResourceGroup map[string][]armcognitiveservices.Account) map[string][]cognitiveAccount {
result := make(map[string][]cognitiveAccount)
for resourceGroup, cogAccounts := range accountsByResourceGroup {
for _, cogAccount := range cogAccounts {
kindName := *cogAccount.Kind
_, exists := result[kindName]
if exists {
result[kindName] = append(result[kindName], cognitiveAccount{
account: cogAccount,
resourceGroup: resourceGroup,
})
} else {
result[kindName] = []cognitiveAccount{{
account: cogAccount,
resourceGroup: resourceGroup,
}}
}
}
}
return result
}
// findCompletedDeployments finds the most recent deployment the given environment in the provided scope,
// considering only deployments which have completed (either successfully or unsuccessfully).
func (p *BicepProvider) findCompletedDeployments(
ctx context.Context, envName string, scope infra.Scope, hint string,
) ([]*armresources.DeploymentExtended, error) {
deployments, err := scope.ListDeployments(ctx)
if err != nil {
return nil, err
}
slices.SortFunc(deployments, func(x, y *armresources.DeploymentExtended) int {
return x.Properties.Timestamp.Compare(*y.Properties.Timestamp)
})
// If hint is not provided, use the environment name as the hint
if hint == "" {
hint = envName
}
// Environment matching strategy
// 1. Deployment with azd tagged env name
// 2. Exact match on environment name to deployment name (old azd strategy)
// 3. Multiple matching names based on specified hint (show user prompt)
matchingDeployments := []*armresources.DeploymentExtended{}
for _, deployment := range deployments {
// We only want to consider deployments that are in a terminal state, not any which may be ongoing.
if *deployment.Properties.ProvisioningState != armresources.ProvisioningStateSucceeded &&
*deployment.Properties.ProvisioningState != armresources.ProvisioningStateFailed {
continue
}
// Match on current azd strategy (tags) or old azd strategy (deployment name)
if v, has := deployment.Tags[azure.TagKeyAzdEnvName]; has && *v == envName || *deployment.Name == envName {
return []*armresources.DeploymentExtended{deployment}, nil
}
// Fallback: Match on hint
if hint != "" && strings.Contains(*deployment.Name, hint) {
matchingDeployments = append(matchingDeployments, deployment)
}
}
if len(matchingDeployments) == 0 {
return nil, fmt.Errorf("no deployments found for environment %s", envName)
}
return matchingDeployments, nil
}
func getDeploymentOptions(ctx context.Context, deployments []*armresources.DeploymentExtended) []string {
promptValues := []string{}
for index, deployment := range deployments {
optionTitle := fmt.Sprintf("%d. %s (%s)",
index+1,
*deployment.Name,
deployment.Properties.Timestamp.Local().Format("1/2/2006, 3:04 PM"),
)
promptValues = append(promptValues, optionTitle)
}
return promptValues
}
// resourceGroupsToDelete collects the resource groups from an existing deployment which should be removed as part of a
// destroy operation.
func resourceGroupsToDelete(deployment *armresources.DeploymentExtended) []string {
// NOTE: it's possible for a deployment to list a resource group more than once. We're only interested in the
// unique set.
resourceGroups := map[string]struct{}{}
if *deployment.Properties.ProvisioningState == armresources.ProvisioningStateSucceeded {
// For a successful deployment, we can use the output resources property to see the resource groups that were
// provisioned from this.
for _, resourceId := range deployment.Properties.OutputResources {
if resourceId != nil && resourceId.ID != nil {
resId, err := arm.ParseResourceID(*resourceId.ID)
if err == nil && resId.ResourceGroupName != "" {
resourceGroups[resId.ResourceGroupName] = struct{}{}
}
}
}
} else {
// For a failed deployment, the `outputResources` field is not populated. Instead, we assume that any resource
// groups which this deployment itself deployed into should be deleted. This matches what a deployment likes
// for the common pattern of having a subscription level deployment which allocates a set of resource groups
// and then does nested deployments into them.
for _, dependency := range deployment.Properties.Dependencies {
if *dependency.ResourceType == string(infra.AzureResourceTypeDeployment) {
for _, dependent := range dependency.DependsOn {
if *dependent.ResourceType == arm.ResourceGroupResourceType.String() {
resourceGroups[*dependent.ResourceName] = struct{}{}
}
}
}
}
}
return maps.Keys(resourceGroups)
}
func (p *BicepProvider) getAllResourcesToDelete(
ctx context.Context,
resourceGroups []string,
) (map[string][]azcli.AzCliResource, error) {
allResources := map[string][]azcli.AzCliResource{}
for _, resourceGroup := range resourceGroups {
groupResources, err := p.azCli.ListResourceGroupResources(ctx, p.env.GetSubscriptionId(), resourceGroup, nil)
var errDetails *azcore.ResponseError
if errors.As(err, &errDetails) && errDetails.StatusCode == 404 {
// Resource group not found and already deleted, skip grouping for deletion
continue
}
if err != nil {
return allResources, err
}
allResources[resourceGroup] = groupResources
}
return allResources, nil
}
func generateResourceGroupsToDelete(groupedResources map[string][]azcli.AzCliResource, subId string) []string {
lines := []string{"Resource group(s) to be deleted:", ""}
for rg := range groupedResources {
lines = append(lines, fmt.Sprintf(
" • %s: %s",
rg,
output.WithLinkFormat("https://portal.azure.com/#@/resource/subscriptions/%s/resourceGroups/%s/overview",
subId,
rg,
),
))
}
return append(lines, "")
}
// Deletes the azure resources within the deployment
func (p *BicepProvider) destroyResourceGroups(
ctx context.Context,
options DestroyOptions,
groupedResources map[string][]azcli.AzCliResource,
resourceCount int,
) error {
if !options.Force() {
p.console.MessageUxItem(ctx, &ux.MultilineMessage{
Lines: generateResourceGroupsToDelete(groupedResources, p.env.GetSubscriptionId())},
)
confirmDestroy, err := p.console.Confirm(ctx, input.ConsoleOptions{
Message: fmt.Sprintf(
"Total resources to %s: %d, are you sure you want to continue?",
output.WithErrorFormat("delete"),
resourceCount,
),
DefaultValue: false,
})
if err != nil {
return fmt.Errorf("prompting for delete confirmation: %w", err)
}
if !confirmDestroy {
return errors.New("user denied delete confirmation")
}
}
p.console.Message(ctx, output.WithGrayFormat("Deleting your resources can take some time.\n"))
for resourceGroup := range groupedResources {
message := fmt.Sprintf("Deleting resource group: %s",
output.WithHighLightFormat(resourceGroup),
)
p.console.ShowSpinner(ctx, message, input.Step)
err := p.azCli.DeleteResourceGroup(ctx, p.env.GetSubscriptionId(), resourceGroup)
p.console.StopSpinner(ctx, message, input.GetStepResultFormat(err))
if err != nil {
return err
}
}
// empty line at the end of all resource group deletion
p.console.Message(ctx, "")
return nil
}
func itemsCountAsText(items []itemToPurge) string {
count := len(items)
if count < 1 {
log.Panic("calling itemsCountAsText() with empty list.")
}
var tokens []string
for _, item := range items {
if item.count > 0 {
tokens = append(tokens, fmt.Sprintf("%d %s", item.count, item.resourceType))
}
}
return ux.ListAsText(tokens)
}
func (p *BicepProvider) purgeItems(
ctx context.Context,
items []itemToPurge,
options DestroyOptions,
) error {
if len(items) == 0 {
// nothing to purge
return nil
}
skipPurge := false
if !options.Purge() {
p.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: fmt.Sprintf(
"The following operation will delete %s.",
itemsCountAsText(items),
),
})
p.console.Message(ctx, fmt.Sprintf(
"These resources have soft delete enabled allowing them to be recovered for a period or time "+
"after deletion. During this period, their names may not be reused. In the future, you cant use "+
"the argument %s to skip this confirmation.\n", output.WithHighLightFormat("--purge")))
purgeItems, err := p.console.Confirm(ctx, input.ConsoleOptions{
Message: fmt.Sprintf(
"Would you like to %s these resources instead, allowing their names to be reused?",
output.WithErrorFormat("permanently delete"),
),
DefaultValue: false,
})
p.console.Message(ctx, "")
if err != nil {
return fmt.Errorf("prompting for confirmation: %w", err)
}
if !purgeItems {
skipPurge = true
}
if err != nil {
return err
}
}
for index, item := range items {
if err := item.purge(skipPurge, &items[index]); err != nil {
return fmt.Errorf("failed to purge %s: %w", item.resourceType, err)