-
Notifications
You must be signed in to change notification settings - Fork 178
/
deployments.go
524 lines (458 loc) · 15.9 KB
/
deployments.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azapi
import (
"context"
"errors"
"fmt"
"io"
"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/resources/armresources"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/azure"
)
type Deployments interface {
ListSubscriptionDeployments(
ctx context.Context,
subscriptionId string,
) ([]*armresources.DeploymentExtended, error)
GetSubscriptionDeployment(
ctx context.Context,
subscriptionId string,
deploymentName string,
) (*armresources.DeploymentExtended, error)
ListResourceGroupDeployments(
ctx context.Context,
subscriptionId string,
resourceGroupName string,
) ([]*armresources.DeploymentExtended, error)
GetResourceGroupDeployment(
ctx context.Context,
subscriptionId string,
resourceGroupName string,
deploymentName string,
) (*armresources.DeploymentExtended, error)
DeployToSubscription(
ctx context.Context,
subscriptionId string,
location string,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
tags map[string]*string,
) (*armresources.DeploymentExtended, error)
DeployToResourceGroup(
ctx context.Context,
subscriptionId,
resourceGroup,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
tags map[string]*string,
) (*armresources.DeploymentExtended, error)
WhatIfDeployToSubscription(
ctx context.Context,
subscriptionId string,
location string,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
) (*armresources.WhatIfOperationResult, error)
WhatIfDeployToResourceGroup(
ctx context.Context,
subscriptionId,
resourceGroup,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
) (*armresources.WhatIfOperationResult, error)
DeleteSubscriptionDeployment(ctx context.Context, subscriptionId string, deploymentName string) error
CalculateTemplateHash(
ctx context.Context,
subscriptionId string,
template azure.RawArmTemplate) (armresources.DeploymentsClientCalculateTemplateHashResponse, error)
}
var (
ErrDeploymentNotFound = errors.New("deployment not found")
)
type deployments struct {
credentialProvider account.SubscriptionCredentialProvider
armClientOptions *arm.ClientOptions
}
func NewDeployments(
credentialProvider account.SubscriptionCredentialProvider,
armClientOptions *arm.ClientOptions,
) Deployments {
return &deployments{
credentialProvider: credentialProvider,
armClientOptions: armClientOptions,
}
}
func (ds *deployments) CalculateTemplateHash(
ctx context.Context,
subscriptionId string,
template azure.RawArmTemplate) (result armresources.DeploymentsClientCalculateTemplateHashResponse, err error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return result, fmt.Errorf("creating deployments client: %w", err)
}
return deploymentClient.CalculateTemplateHash(ctx, template, nil)
}
func (ds *deployments) ListSubscriptionDeployments(
ctx context.Context,
subscriptionId string,
) ([]*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
results := []*armresources.DeploymentExtended{}
pager := deploymentClient.NewListAtSubscriptionScopePager(nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, err
}
results = append(results, page.Value...)
}
return results, nil
}
func (ds *deployments) GetSubscriptionDeployment(
ctx context.Context,
subscriptionId string,
deploymentName string,
) (*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
deployment, err := deploymentClient.GetAtSubscriptionScope(ctx, deploymentName, nil)
if err != nil {
var errDetails *azcore.ResponseError
if errors.As(err, &errDetails) && errDetails.StatusCode == 404 {
return nil, ErrDeploymentNotFound
}
return nil, fmt.Errorf("getting deployment from subscription: %w", err)
}
return &deployment.DeploymentExtended, nil
}
func (ds *deployments) ListResourceGroupDeployments(
ctx context.Context,
subscriptionId string,
resourceGroupName string,
) ([]*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
results := []*armresources.DeploymentExtended{}
pager := deploymentClient.NewListByResourceGroupPager(resourceGroupName, nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, err
}
results = append(results, page.Value...)
}
return results, nil
}
func (ds *deployments) GetResourceGroupDeployment(
ctx context.Context,
subscriptionId string,
resourceGroupName string,
deploymentName string,
) (*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
deployment, err := deploymentClient.Get(ctx, resourceGroupName, deploymentName, nil)
if err != nil {
var errDetails *azcore.ResponseError
if errors.As(err, &errDetails) && errDetails.StatusCode == 404 {
return nil, ErrDeploymentNotFound
}
return nil, fmt.Errorf("getting deployment from resource group: %w", err)
}
return &deployment.DeploymentExtended, nil
}
func (ds *deployments) createDeploymentsClient(
ctx context.Context,
subscriptionId string,
) (*armresources.DeploymentsClient, error) {
credential, err := ds.credentialProvider.CredentialForSubscription(ctx, subscriptionId)
if err != nil {
return nil, err
}
client, err := armresources.NewDeploymentsClient(subscriptionId, credential, ds.armClientOptions)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
return client, nil
}
func (ds *deployments) DeployToSubscription(
ctx context.Context,
subscriptionId string,
location string,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
tags map[string]*string,
) (*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
createFromTemplateOperation, err := deploymentClient.BeginCreateOrUpdateAtSubscriptionScope(
ctx, deploymentName,
armresources.Deployment{
Properties: &armresources.DeploymentProperties{
Template: armTemplate,
Parameters: parameters,
Mode: to.Ptr(armresources.DeploymentModeIncremental),
},
Location: to.Ptr(location),
Tags: tags,
}, nil)
if err != nil {
return nil, fmt.Errorf("starting deployment to subscription: %w", err)
}
// wait for deployment creation
deployResult, err := createFromTemplateOperation.PollUntilDone(ctx, nil)
if err != nil {
deploymentError := createDeploymentError(err)
return nil, fmt.Errorf(
"deploying to subscription:\n\nDeployment Error Details:\n%w",
deploymentError,
)
}
return &deployResult.DeploymentExtended, nil
}
func (ds *deployments) DeployToResourceGroup(
ctx context.Context,
subscriptionId, resourceGroup, deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
tags map[string]*string,
) (*armresources.DeploymentExtended, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
createFromTemplateOperation, err := deploymentClient.BeginCreateOrUpdate(
ctx, resourceGroup, deploymentName,
armresources.Deployment{
Properties: &armresources.DeploymentProperties{
Template: armTemplate,
Parameters: parameters,
Mode: to.Ptr(armresources.DeploymentModeIncremental),
},
Tags: tags,
}, nil)
if err != nil {
return nil, fmt.Errorf("starting deployment to resource group: %w", err)
}
// wait for deployment creation
deployResult, err := createFromTemplateOperation.PollUntilDone(ctx, nil)
if err != nil {
deploymentError := createDeploymentError(err)
return nil, fmt.Errorf(
"deploying to resource group:\n\nDeployment Error Details:\n%w",
deploymentError,
)
}
return &deployResult.DeploymentExtended, nil
}
func (ds *deployments) WhatIfDeployToSubscription(
ctx context.Context,
subscriptionId string,
location string,
deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
) (*armresources.WhatIfOperationResult, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
createFromTemplateOperation, err := deploymentClient.BeginWhatIfAtSubscriptionScope(
ctx, deploymentName,
armresources.DeploymentWhatIf{
Properties: &armresources.DeploymentWhatIfProperties{
Template: armTemplate,
Parameters: parameters,
Mode: to.Ptr(armresources.DeploymentModeIncremental),
WhatIfSettings: &armresources.DeploymentWhatIfSettings{},
},
Location: to.Ptr(location),
}, nil)
if err != nil {
return nil, fmt.Errorf("starting deployment to subscription: %w", err)
}
// wait for deployment creation
deployResult, err := createFromTemplateOperation.PollUntilDone(ctx, nil)
if err != nil {
deploymentError := createDeploymentError(err)
return nil, fmt.Errorf(
"deploying to subscription:\n\nDeployment Error Details:\n%w",
deploymentError,
)
}
return &deployResult.WhatIfOperationResult, nil
}
func (ds *deployments) WhatIfDeployToResourceGroup(
ctx context.Context,
subscriptionId, resourceGroup, deploymentName string,
armTemplate azure.RawArmTemplate,
parameters azure.ArmParameters,
) (*armresources.WhatIfOperationResult, error) {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return nil, fmt.Errorf("creating deployments client: %w", err)
}
createFromTemplateOperation, err := deploymentClient.BeginWhatIf(
ctx, resourceGroup, deploymentName,
armresources.DeploymentWhatIf{
Properties: &armresources.DeploymentWhatIfProperties{
Template: armTemplate,
Parameters: parameters,
Mode: to.Ptr(armresources.DeploymentModeIncremental),
},
}, nil)
if err != nil {
return nil, fmt.Errorf("starting deployment to resource group: %w", err)
}
// wait for deployment creation
deployResult, err := createFromTemplateOperation.PollUntilDone(ctx, nil)
if err != nil {
deploymentError := createDeploymentError(err)
return nil, fmt.Errorf(
"deploying to resource group:\n\nDeployment Error Details:\n%w",
deploymentError,
)
}
return &deployResult.WhatIfOperationResult, nil
}
func (ds *deployments) DeleteSubscriptionDeployment(
ctx context.Context, subscriptionId string, deploymentName string) error {
deploymentClient, err := ds.createDeploymentsClient(ctx, subscriptionId)
if err != nil {
return fmt.Errorf("deleting deployment: %w", err)
}
deleteDeploymentOperation, err := deploymentClient.BeginDeleteAtSubscriptionScope(ctx, deploymentName, nil)
if err != nil {
return fmt.Errorf("starting to delete deployment: %w", err)
}
// wait for the operation to complete
_, err = deleteDeploymentOperation.PollUntilDone(ctx, nil)
if err != nil {
return fmt.Errorf("deleting deployment operation: %w", err)
}
return nil
}
type AzCliDeploymentPropertiesDependency struct {
AzCliDeploymentPropertiesBasicDependency
DependsOn []AzCliDeploymentPropertiesBasicDependency `json:"dependsOn"`
}
type AzCliDeploymentPropertiesBasicDependency struct {
Id string `json:"id"`
ResourceName string `json:"resourceName"`
ResourceType string `json:"resourceType"`
}
type AzCliDeploymentErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Target string `json:"target"`
Details []AzCliDeploymentErrorResponse `json:"details"`
AdditionalInfo AzCliDeploymentAdditionalInfo `json:"additionalInfo"`
}
type AzCliDeploymentAdditionalInfo struct {
Type string `json:"type"`
Info interface{} `json:"info"`
}
type AzCliDeployment struct {
Id string `json:"id"`
Name string `json:"name"`
Properties AzCliDeploymentProperties `json:"properties"`
}
type AzCliDeploymentProperties struct {
CorrelationId string `json:"correlationId"`
Error AzCliDeploymentErrorResponse `json:"error"`
Dependencies []AzCliDeploymentPropertiesDependency `json:"dependencies"`
OutputResources []AzCliDeploymentResourceReference `json:"outputResources"`
Outputs map[string]AzCliDeploymentOutput `json:"outputs"`
}
type AzCliDeploymentResourceReference struct {
Id string `json:"id"`
}
type AzCliDeploymentOutput struct {
Type string `json:"type"`
Value interface{} `json:"value"`
}
type AzCliDeploymentResult struct {
Properties AzCliDeploymentResultProperties `json:"properties"`
}
type AzCliDeploymentResultProperties struct {
Outputs map[string]AzCliDeploymentOutput `json:"outputs"`
}
type AzCliResourceOperation struct {
Id string `json:"id"`
OperationId string `json:"operationId"`
Properties AzCliResourceOperationProperties `json:"properties"`
}
type AzCliResourceOperationProperties struct {
ProvisioningOperation string `json:"provisioningOperation"`
ProvisioningState string `json:"provisioningState"`
TargetResource AzCliResourceOperationTargetResource `json:"targetResource"`
StatusCode string `json:"statusCode"`
StatusMessage AzCliDeploymentStatusMessage `json:"statusMessage"`
// While the operation is in progress, this timestamp effectively represents "InProgressTimestamp".
// When the operation ends, this timestamp effectively represents "EndTimestamp".
Timestamp time.Time `json:"timestamp"`
}
type AzCliResourceOperationTargetResource struct {
Id string `json:"id"`
ResourceType string `json:"resourceType"`
ResourceName string `json:"resourceName"`
ResourceGroup string `json:"resourceGroup"`
}
type AzCliDeploymentStatusMessage struct {
Err AzCliDeploymentErrorResponse `json:"error"`
Status string `json:"status"`
}
// convert from: sdk client outputs: interface{} to map[string]azapi.AzCliDeploymentOutput
// sdk client parses http response from network as an interface{}
// this function keeps the compatibility with the previous AzCliDeploymentOutput model
func CreateDeploymentOutput(rawOutputs interface{}) (result map[string]AzCliDeploymentOutput) {
if rawOutputs == nil {
return make(map[string]AzCliDeploymentOutput, 0)
}
castInput := rawOutputs.(map[string]interface{})
result = make(map[string]AzCliDeploymentOutput, len(castInput))
for key, output := range castInput {
innerValue := output.(map[string]interface{})
result[key] = AzCliDeploymentOutput{
Type: innerValue["type"].(string),
Value: innerValue["value"],
}
}
return result
}
// Attempts to create an Azure Deployment error from the HTTP response error
func createDeploymentError(err error) error {
var responseErr *azcore.ResponseError
if errors.As(err, &responseErr) {
var errorText string
rawBody, err := io.ReadAll(responseErr.RawResponse.Body)
if err != nil {
errorText = responseErr.Error()
} else {
errorText = string(rawBody)
}
return NewAzureDeploymentError(errorText)
}
return err
}