-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathbicep_provider.go
2088 lines (1807 loc) · 66.3 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"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log"
"maps"
"math"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"time"
"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-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/async"
"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/cloud"
"github.com/azure/azure-dev/cli/azd/pkg/cmdsubst"
"github.com/azure/azure-dev/cli/azd/pkg/config"
"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/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/password"
"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/bicep"
"github.com/drone/envsubst"
)
const (
defaultModule = "main"
defaultPath = "infra"
)
type deploymentDetails struct {
CompiledBicep *compileBicepResult
// 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
envManager environment.Manager
projectPath string
options provisioning.Options
console input.Console
bicepCli *bicep.Cli
azapi *azapi.AzureClient
resourceService *azapi.ResourceService
deploymentManager *infra.DeploymentManager
prompters prompt.Prompter
curPrincipal provisioning.CurrentPrincipalIdProvider
ignoreDeploymentState bool
// compileBicepResult is cached to avoid recompiling the same bicep file multiple times in the same azd run.
compileBicepMemoryCache *compileBicepResult
keyvaultService keyvault.KeyVaultService
portalUrlBase string
}
// Name gets the name of the infra provider
func (p *BicepProvider) Name() string {
return "Bicep"
}
func (p *BicepProvider) RequiredExternalTools() []tools.ExternalTool {
return []tools.ExternalTool{}
}
// Initialize initializes provider state from the options.
// It also calls EnsureEnv, which ensures the client-side state is ready for provisioning.
func (p *BicepProvider) Initialize(ctx context.Context, projectPath string, options provisioning.Options) error {
p.projectPath = projectPath
p.options = options
if p.options.Module == "" {
p.options.Module = defaultModule
}
if p.options.Path == "" {
p.options.Path = defaultPath
}
requiredTools := p.RequiredExternalTools()
if err := tools.EnsureInstalled(ctx, requiredTools...); err != nil {
return err
}
p.ignoreDeploymentState = options.IgnoreDeploymentState
p.console.ShowSpinner(ctx, "Initialize bicep provider", input.Step)
err := p.EnsureEnv(ctx)
p.console.StopSpinner(ctx, "", input.Step)
return err
}
var ErrEnsureEnvPreReqBicepCompileFailed = errors.New("")
// EnsureEnv ensures that the environment is in a provision-ready state with required values set, prompting the user if
// values are unset. This also requires that the Bicep module can be compiled.
func (p *BicepProvider) EnsureEnv(ctx context.Context) error {
modulePath := p.modulePath()
// for .bicepparam, we first prompt for environment values before calling compiling bicepparam file
// which can reference these values
if isBicepParamFile(modulePath) {
if err := provisioning.EnsureSubscriptionAndLocation(ctx, p.envManager, p.env, p.prompters, nil); err != nil {
return err
}
}
compileResult, compileErr := p.compileBicep(ctx, modulePath)
if compileErr != nil {
return fmt.Errorf("%w%w", ErrEnsureEnvPreReqBicepCompileFailed, compileErr)
}
// for .bicep, azd must load a parameters.json file and create the ArmParameters
if isBicepFile(modulePath) {
var filterLocation = func(loc account.Location) bool {
if locationParam, defined := compileResult.Template.Parameters["location"]; defined {
if locationParam.AllowedValues != nil {
return slices.IndexFunc(*locationParam.AllowedValues, func(allowedValue any) bool {
allowedValueString, goodCast := allowedValue.(string)
return goodCast && loc.Name == allowedValueString
}) != -1
}
}
return true
}
err := provisioning.EnsureSubscriptionAndLocation(ctx, p.envManager, p.env, p.prompters, filterLocation)
if err != nil {
return err
}
if _, err := p.ensureParameters(ctx, compileResult.Template); err != nil {
return err
}
}
scope, err := compileResult.Template.TargetScope()
if err != nil {
return err
}
if scope == azure.DeploymentScopeResourceGroup {
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.envManager.Save(ctx, p.env); err != nil {
return fmt.Errorf("saving resource group name: %w", err)
}
}
}
return nil
}
func (p *BicepProvider) LastDeployment(ctx context.Context) (*azapi.ResourceDeployment, error) {
modulePath := p.modulePath()
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, fmt.Errorf("compiling bicep template: %w", err)
}
scope, err := p.scopeForTemplate(compileResult.Template)
if err != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
return p.latestDeploymentResult(ctx, scope)
}
func (p *BicepProvider) State(ctx context.Context, options *provisioning.StateOptions) (*provisioning.StateResult, error) {
if options == nil {
options = &provisioning.StateOptions{}
}
var err error
spinnerMessage := "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(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()
if scopeErr != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
outputs = azure.ArmTemplateOutputs{}
}
spinnerMessage = "Retrieving Azure deployment"
p.console.ShowSpinner(ctx, spinnerMessage, input.Step)
var deployment *azapi.ResourceDeployment
deployments, err := p.deploymentManager.CompletedDeployments(ctx, scope, p.env.Name(), 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(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 := provisioning.State{}
state.Resources = make([]provisioning.Resource, len(deployment.Resources))
for idx, res := range deployment.Resources {
state.Resources[idx] = provisioning.Resource{
Id: *res.ID,
}
}
state.Outputs = p.createOutputParameters(
outputs,
azapi.CreateDeploymentOutput(deployment.Outputs),
)
p.console.MessageUxItem(ctx, &ux.DoneMessage{
Message: fmt.Sprintf("Updated %d environment variables", len(state.Outputs)),
})
outputsUrl, err := azdDeployment.OutputsUrl(ctx)
if err != nil {
return nil, err
}
p.console.Message(ctx, fmt.Sprintf(
"\nPopulated environment from Azure infrastructure deployment: %s",
output.WithHyperlink(outputsUrl, deployment.Name),
))
return &provisioning.StateResult{
State: &state,
}, nil
}
func (p *BicepProvider) createDeploymentFromArmDeployment(
scope infra.Scope,
deploymentName string,
) (infra.Deployment, error) {
resourceGroupScope, ok := scope.(*infra.ResourceGroupScope)
if ok {
return p.deploymentManager.ResourceGroupDeployment(resourceGroupScope, deploymentName), nil
}
subscriptionScope, ok := scope.(*infra.SubscriptionScope)
if ok {
return p.deploymentManager.SubscriptionDeployment(subscriptionScope, deploymentName), nil
}
return nil, errors.New("unsupported deployment scope")
}
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) (*deploymentDetails, error) {
p.console.ShowSpinner(ctx, "Creating a deployment plan", input.Step)
modulePath := p.modulePath()
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, fmt.Errorf("creating template: %w", err)
}
// for .bicep, azd must load a parameters.json file and create the ArmParameters
if isBicepFile(modulePath) {
configuredParameters, err := p.ensureParameters(ctx, compileResult.Template)
if err != nil {
return nil, err
}
compileResult.Parameters = configuredParameters
}
deploymentScope, err := compileResult.Template.TargetScope()
if err != nil {
return nil, err
}
target, err := p.deploymentFromScopeType(deploymentScope)
if err != nil {
return nil, err
}
return &deploymentDetails{
CompiledBicep: compileResult,
Target: target,
}, nil
}
func (p *BicepProvider) deploymentFromScopeType(deploymentScopeType azure.DeploymentScope) (infra.Deployment, error) {
deploymentName := p.deploymentManager.GenerateDeploymentName(p.env.Name())
if deploymentScopeType == azure.DeploymentScopeSubscription {
scope := p.deploymentManager.SubscriptionScope(p.env.GetSubscriptionId(), p.env.GetLocation())
return infra.NewSubscriptionDeployment(
scope,
deploymentName,
), nil
} else if deploymentScopeType == azure.DeploymentScopeResourceGroup {
scope := p.deploymentManager.ResourceGroupScope(
p.env.GetSubscriptionId(),
p.env.Getenv(environment.ResourceGroupEnvVarName),
)
return infra.NewResourceGroupDeployment(scope, deploymentName), nil
}
return nil, fmt.Errorf("unsupported scope: %s", deploymentScopeType)
}
// deploymentState returns the latests deployment if it is the same as the deployment within deploymentData or an error
// otherwise.
func (p *BicepProvider) deploymentState(
ctx context.Context,
deploymentData *deploymentDetails,
currentParamsHash string,
) (*azapi.ResourceDeployment, error) {
p.console.ShowSpinner(ctx, "Comparing deployment state", input.Step)
prevDeploymentResult, err := p.latestDeploymentResult(ctx, deploymentData.Target)
if err != nil {
return nil, fmt.Errorf("deployment state error: %w", err)
}
// State is invalid if the last deployment was not succeeded
// This is currently safe because we rely on latestDeploymentResult which
// relies on findCompletedDeployments which filters to only Failed and Succeeded
if prevDeploymentResult.ProvisioningState != azapi.DeploymentProvisioningStateSucceeded {
return nil, fmt.Errorf("last deployment failed.")
}
templateHash, err := p.deploymentManager.CalculateTemplateHash(
ctx, p.env.GetSubscriptionId(),
deploymentData.CompiledBicep.RawArmTemplate,
)
if err != nil {
return nil, fmt.Errorf("can't get hash from current template: %w", err)
}
if !prevDeploymentEqualToCurrent(prevDeploymentResult, templateHash, currentParamsHash) {
return nil, fmt.Errorf("deployment state has changed")
}
return prevDeploymentResult, nil
}
// latestDeploymentResult looks and finds a previous deployment for the current azd project.
func (p *BicepProvider) latestDeploymentResult(
ctx context.Context,
scope infra.Scope,
) (*azapi.ResourceDeployment, error) {
deployments, err := p.deploymentManager.CompletedDeployments(ctx, scope, p.env.Name(), "")
// findCompletedDeployments returns error if no deployments are found
// No need to check for empty list
if err != nil {
return nil, err
}
if len(deployments) > 1 {
// If more than one deployment found, ignore the prev-deployment
return nil, fmt.Errorf("more than one previous deployment match.")
}
return deployments[0], nil
}
// parametersHash generates a hash from its name and final value.
// The final value is either the parameter default value or the value from the params input.
func parametersHash(templateParameters azure.ArmTemplateParameterDefinitions, params azure.ArmParameters) (string, error) {
hash256 := sha256.New()
// Get the parameter name and its final value.
// Any other change on the parameter definition would break the template-hash
nameAndValueParams := make(map[string]any, len(templateParameters))
for paramName, paramDefinition := range templateParameters {
pValue := paramDefinition.DefaultValue
if param, exists := params[paramName]; exists {
pValue = param.Value
}
nameAndValueParams[paramName] = pValue
}
nameAndValueParamsBytes, err := json.Marshal(nameAndValueParams)
if err != nil {
return "", err
}
if _, err := hash256.Write(nameAndValueParamsBytes); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash256.Sum(nil)), nil
}
// prevDeploymentEqualToCurrent compares the template hash from a previous deployment against a current template.
func prevDeploymentEqualToCurrent(prev *azapi.ResourceDeployment, templateHash, paramsHash string) bool {
if prev == nil {
logDS("No previous deployment.")
return false
}
if prev.Tags == nil {
logDS("No previous deployment params tags")
return false
}
prevTemplateHash := convert.ToValueWithDefault(prev.TemplateHash, "")
if prevTemplateHash != templateHash {
logDS("template hash is different from previous deployment")
return false
}
prevParamHash, hasTag := prev.Tags[azure.TagKeyAzdDeploymentStateParamHashName]
if !hasTag {
logDS("no param hash tag on last deployment.")
return false
}
if *prevParamHash != paramsHash {
logDS("template parameters are different from previous deployment")
return false
}
logDS("Previous deployment state is equal to current deployment. Deployment can be skipped.")
return true
}
func logDS(msg string, v ...any) {
log.Printf("%s : %s", "deployment-state: ", fmt.Sprintf(msg, v...))
}
// Provisioning the infrastructure within the specified template
func (p *BicepProvider) Deploy(ctx context.Context) (*provisioning.DeployResult, error) {
if p.ignoreDeploymentState {
logDS("Azure Deployment State is disabled by --no-state arg.")
}
bicepDeploymentData, err := p.plan(ctx)
if err != nil {
return nil, err
}
deployment, err := p.convertToDeployment(bicepDeploymentData.CompiledBicep.Template)
if err != nil {
return nil, err
}
// parameters hash is required for doing deployment state validation check but also to set the hash
// after a successful deployment.
currentParamsHash, parametersHashErr := parametersHash(
bicepDeploymentData.CompiledBicep.Template.Parameters, bicepDeploymentData.CompiledBicep.Parameters)
if parametersHashErr != nil {
// fail to hash parameters won't stop the operation. It only disables deployment state and recording parameters hash
logDS("%s", parametersHashErr.Error())
}
if !p.ignoreDeploymentState && parametersHashErr == nil {
deploymentState, err := p.deploymentState(ctx, bicepDeploymentData, currentParamsHash)
if err == nil {
deployment.Outputs = p.createOutputParameters(
bicepDeploymentData.CompiledBicep.Template.Outputs,
azapi.CreateDeploymentOutput(deploymentState.Outputs),
)
return &provisioning.DeployResult{
Deployment: deployment,
SkippedReason: provisioning.DeploymentStateSkipped,
}, nil
}
logDS("%s", err.Error())
}
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
progressDisplay := p.deploymentManager.ProgressDisplay(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)
deploymentTags := map[string]*string{
azure.TagKeyAzdEnvName: to.Ptr(p.env.Name()),
}
if parametersHashErr == nil {
deploymentTags[azure.TagKeyAzdDeploymentStateParamHashName] = to.Ptr(currentParamsHash)
}
optionsMap, err := convert.ToMap(p.options)
if err != nil {
return nil, err
}
deployResult, err := p.deployModule(
ctx,
bicepDeploymentData.Target,
bicepDeploymentData.CompiledBicep.RawArmTemplate,
bicepDeploymentData.CompiledBicep.Parameters,
deploymentTags,
optionsMap,
)
if err != nil {
return nil, err
}
deployment.Outputs = p.createOutputParameters(
bicepDeploymentData.CompiledBicep.Template.Outputs,
azapi.CreateDeploymentOutput(deployResult.Outputs),
)
return &provisioning.DeployResult{
Deployment: deployment,
}, nil
}
// Preview runs deploy using the what-if argument
func (p *BicepProvider) Preview(ctx context.Context) (*provisioning.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.CompiledBicep.RawArmTemplate,
bicepDeploymentData.CompiledBicep.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 []*provisioning.DeploymentPreviewChange
for _, change := range deployPreviewResult.Properties.Changes {
resourceAfter := change.After.(map[string]interface{})
changes = append(changes, &provisioning.DeploymentPreviewChange{
ChangeType: provisioning.ChangeType(*change.ChangeType),
ResourceId: provisioning.Resource{
Id: *change.ResourceID,
},
ResourceType: resourceAfter["type"].(string),
Name: resourceAfter["name"].(string),
})
}
return &provisioning.DeployPreviewResult{
Preview: &provisioning.DeploymentPreview{
Status: *deployPreviewResult.Status,
Properties: &provisioning.DeploymentPreviewProperties{
Changes: changes,
},
},
}, nil
}
type itemToPurge struct {
resourceType string
count int
purge func(skipPurge bool, self *itemToPurge) error
cognitiveAccounts []cognitiveAccount
}
func (p *BicepProvider) scopeForTemplate(t azure.ArmTemplate) (infra.Scope, error) {
deploymentScope, err := t.TargetScope()
if err != nil {
return nil, err
}
if deploymentScope == azure.DeploymentScopeSubscription {
return p.deploymentManager.SubscriptionScope(p.env.GetSubscriptionId(), p.env.GetLocation()), nil
} else if deploymentScope == azure.DeploymentScopeResourceGroup {
return p.deploymentManager.ResourceGroupScope(
p.env.GetSubscriptionId(),
p.env.Getenv(environment.ResourceGroupEnvVarName),
), nil
} else {
return nil, fmt.Errorf("unsupported deployment scope: %s", deploymentScope)
}
}
func (p *BicepProvider) inferScopeFromEnv() (infra.Scope, error) {
if resourceGroup, has := p.env.LookupEnv(environment.ResourceGroupEnvVarName); has {
return p.deploymentManager.ResourceGroupScope(p.env.GetSubscriptionId(), resourceGroup), nil
} else {
return p.deploymentManager.SubscriptionScope(p.env.GetSubscriptionId(), p.env.GetLocation()), nil
}
}
// Destroys the specified deployment by deleting all azure resources, resource groups & deployments that are referenced.
func (p *BicepProvider) Destroy(
ctx context.Context,
options provisioning.DestroyOptions,
) (*provisioning.DestroyResult, error) {
modulePath := p.modulePath()
p.console.ShowSpinner(ctx, "Discovering resources to delete...", input.Step)
defer p.console.StopSpinner(ctx, "", input.StepDone)
compileResult, err := p.compileBicep(ctx, modulePath)
if err != nil {
return nil, fmt.Errorf("creating template: %w", err)
}
scope, err := p.scopeForTemplate(compileResult.Template)
if err != nil {
return nil, fmt.Errorf("computing deployment scope: %w", err)
}
completedDeployments, err := p.deploymentManager.CompletedDeployments(ctx, scope, p.env.Name(), "")
if err != nil {
return nil, fmt.Errorf("finding completed deployments: %w", err)
}
if len(completedDeployments) == 0 {
return nil, fmt.Errorf("no deployments found for environment, '%s'", p.env.Name())
}
mostRecentDeployment := completedDeployments[0]
deploymentToDelete := scope.Deployment(mostRecentDeployment.Name)
resourcesToDelete, err := deploymentToDelete.Resources(ctx)
if err != nil {
return nil, fmt.Errorf("getting resources to delete: %w", err)
}
groupedResources, err := azapi.GroupByResourceGroup(resourcesToDelete)
if err != nil {
return nil, fmt.Errorf("mapping resources to resource groups: %w", err)
}
if len(groupedResources) == 0 {
return nil, fmt.Errorf("%w, '%s'", infra.ErrDeploymentResourcesNotFound, deploymentToDelete.Name())
}
keyVaults, err := p.getKeyVaultsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting key vaults to purge: %w", err)
}
managedHSMs, err := p.getManagedHSMsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting managed hsms to purge: %w", err)
}
appConfigs, err := p.getAppConfigsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting app configurations to purge: %w", err)
}
apiManagements, err := p.getApiManagementsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting API managements to purge: %w", err)
}
cognitiveAccounts, err := p.getCognitiveAccountsToPurge(ctx, groupedResources)
if err != nil {
return nil, fmt.Errorf("getting cognitive accounts to purge: %w", err)
}
p.console.StopSpinner(ctx, "", input.StepDone)
if err := p.destroyDeploymentWithConfirmation(
ctx,
options,
deploymentToDelete,
groupedResources,
len(resourcesToDelete),
); 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, skipPurge)
},
}
managedHSMsPurge := itemToPurge{
resourceType: "Managed HSM",
count: len(managedHSMs),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeManagedHSMs(ctx, managedHSMs, skipPurge)
},
}
appConfigsPurge := itemToPurge{
resourceType: "App Configuration",
count: len(appConfigs),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeAppConfigs(ctx, appConfigs, skipPurge)
},
}
aPIManagement := itemToPurge{
resourceType: "API Management",
count: len(apiManagements),
purge: func(skipPurge bool, self *itemToPurge) error {
return p.purgeAPIManagement(ctx, apiManagements, 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, 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 := &provisioning.DestroyResult{
InvalidatedEnvKeys: slices.Collect(maps.Keys(p.createOutputParameters(
compileResult.Template.Outputs,
azapi.CreateDeploymentOutput(mostRecentDeployment.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
// Replace "FormRecognizer" with "DocumentIntelligence"
if kindName == "FormRecognizer" {
kindName = "Document Intelligence"
}
_, 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
}
func getDeploymentOptions(deployments []*azapi.ResourceDeployment) []string {
promptValues := []string{}
for index, deployment := range deployments {
optionTitle := fmt.Sprintf("%d. %s (%s)",
index+1,
deployment.Name,
deployment.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 *azapi.ResourceDeployment) []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.ProvisioningState == azapi.DeploymentProvisioningStateSucceeded {
// 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.Resources {
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.Dependencies {
if *dependency.ResourceType == string(azapi.AzureResourceTypeDeployment) {
for _, dependent := range dependency.DependsOn {
if *dependent.ResourceType == arm.ResourceGroupResourceType.String() {
resourceGroups[*dependent.ResourceName] = struct{}{}
}
}
}
}
}
return slices.Collect(maps.Keys(resourceGroups))
}
func (p *BicepProvider) generateResourcesToDelete(groupedResources map[string][]*azapi.Resource) []string {
lines := []string{"Resource(s) to be deleted:"}
for resourceGroupName, resources := range groupedResources {
lines = append(lines, "")
// Resource Group
resourceGroupLink := fmt.Sprintf("%s/#@/resource/subscriptions/%s/resourceGroups/%s/overview",
p.portalUrlBase,
p.env.GetSubscriptionId(),
resourceGroupName,
)
lines = append(lines,
fmt.Sprintf("%s %s",
output.WithHighLightFormat("Resource Group:"),
output.WithHyperlink(resourceGroupLink, resourceGroupName),
),
)
// Resources in each group
for _, resource := range resources {
resourceTypeName := azapi.GetResourceTypeDisplayName(azapi.AzureResourceType(resource.Type))
if resourceTypeName == "" {
continue
}
lines = append(lines, fmt.Sprintf(" • %s: %s", resourceTypeName, resource.Name))
}
}
return append(lines, "\n")
}