-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
resource_arm_batch_pool.go
804 lines (703 loc) · 26.6 KB
/
resource_arm_batch_pool.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
package azurerm
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/features"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
"github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2018-12-01/batch"
)
func resourceArmBatchPool() *schema.Resource {
return &schema.Resource{
Create: resourceArmBatchPoolCreate,
Read: resourceArmBatchPoolRead,
Update: resourceArmBatchPoolUpdate,
Delete: resourceArmBatchPoolDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateAzureRMBatchPoolName,
},
// TODO: make this case sensitive once this API bug has been fixed:
// https://github.com/Azure/azure-rest-api-specs/issues/5574
"resource_group_name": azure.SchemaResourceGroupNameDiffSuppress(),
"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureRMBatchAccountName,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"vm_size": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: suppress.CaseDifference,
},
"max_tasks_per_node": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ForceNew: true,
ValidateFunc: validation.IntAtLeast(1),
},
"fixed_scale": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"target_dedicated_nodes": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: validation.IntBetween(0, 2000),
},
"target_low_priority_nodes": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 1000),
},
"resize_timeout": {
Type: schema.TypeString,
Optional: true,
Default: "PT15M",
},
},
},
},
"auto_scale": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"evaluation_interval": {
Type: schema.TypeString,
Optional: true,
Default: "PT15M",
},
"formula": {
Type: schema.TypeString,
Required: true,
DiffSuppressFunc: func(_, old, new string, d *schema.ResourceData) bool {
return strings.TrimSpace(old) == strings.TrimSpace(new)
},
},
},
},
},
"container_configuration": {
Type: schema.TypeList,
Optional: true,
MinItems: 1,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validate.NoEmptyStrings,
},
"container_registries": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
ConfigMode: schema.SchemaConfigModeAttr,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"registry_server": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},
"user_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},
"password": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
ValidateFunc: validate.NoEmptyStrings,
},
},
},
},
},
},
},
"storage_image_reference": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},
"publisher": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},
"offer": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},
"sku": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validate.NoEmptyStrings,
},
"version": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validate.NoEmptyStrings,
},
},
},
},
"node_agent_sku_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"stop_pending_resize_operation": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"certificate": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Required: true,
ValidateFunc: azure.ValidateResourceID,
// The ID returned for the certificate in the batch account and the certificate applied to the pool
// are not consistent in their casing which causes issues when referencing IDs across resources
// (as Terraform still sees differences to apply due to the casing)
// Handling by ignoring casing for now. Raised as an issue: https://github.com/Azure/azure-rest-api-specs/issues/5574
DiffSuppressFunc: suppress.CaseDifference,
},
"store_location": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"CurrentUser",
"LocalMachine",
}, false),
},
"store_name": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validate.NoEmptyStrings,
},
"visibility": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
"StartTask",
"Task",
"RemoteUser",
}, false),
},
},
},
},
},
"start_task": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"command_line": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
"max_task_retry_count": {
Type: schema.TypeInt,
Optional: true,
Default: 1,
},
"wait_for_success": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"environment": {
Type: schema.TypeMap,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"user_identity": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"user_name": {
Type: schema.TypeString,
Optional: true,
},
"auto_user": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"elevation_level": {
Type: schema.TypeString,
Optional: true,
Default: string(batch.NonAdmin),
ValidateFunc: validation.StringInSlice([]string{
string(batch.NonAdmin),
string(batch.Admin),
}, false),
},
"scope": {
Type: schema.TypeString,
Optional: true,
Default: string(batch.AutoUserScopeTask),
ValidateFunc: validation.StringInSlice([]string{
string(batch.AutoUserScopeTask),
string(batch.AutoUserScopePool),
}, false),
},
},
},
},
},
},
},
"resource_file": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"auto_storage_container_name": {
Type: schema.TypeString,
Optional: true,
},
"blob_prefix": {
Type: schema.TypeString,
Optional: true,
},
"file_mode": {
Type: schema.TypeString,
Optional: true,
},
"file_path": {
Type: schema.TypeString,
Optional: true,
},
"http_url": {
Type: schema.TypeString,
Optional: true,
},
"storage_container_url": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
},
},
},
},
}
}
func resourceArmBatchPoolCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).batch.PoolClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for Azure Batch pool creation.")
resourceGroup := d.Get("resource_group_name").(string)
accountName := d.Get("account_name").(string)
poolName := d.Get("name").(string)
displayName := d.Get("display_name").(string)
vmSize := d.Get("vm_size").(string)
maxTasksPerNode := int32(d.Get("max_tasks_per_node").(int))
if features.ShouldResourcesBeImported() && d.IsNewResource() {
existing, err := client.Get(ctx, resourceGroup, accountName, poolName)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of existing Batch Pool %q (Account %q / Resource Group %q): %+v", poolName, accountName, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_batch_pool", *existing.ID)
}
}
parameters := batch.Pool{
PoolProperties: &batch.PoolProperties{
VMSize: &vmSize,
DisplayName: &displayName,
MaxTasksPerNode: &maxTasksPerNode,
},
}
scaleSettings, err := expandBatchPoolScaleSettings(d)
if err != nil {
return fmt.Errorf("Error expanding scale settings: %+v", err)
}
parameters.PoolProperties.ScaleSettings = scaleSettings
nodeAgentSkuID := d.Get("node_agent_sku_id").(string)
storageImageReferenceSet := d.Get("storage_image_reference").([]interface{})
imageReference, err := azure.ExpandBatchPoolImageReference(storageImageReferenceSet)
if err != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
if imageReference != nil {
// if an image reference ID is specified, the user wants use a custom image. This property is mutually exclusive with other properties.
if imageReference.ID != nil && (imageReference.Offer != nil || imageReference.Publisher != nil || imageReference.Sku != nil || imageReference.Version != nil) {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): Properties version, offer, publish cannot be defined when using a custom image id", poolName, resourceGroup)
} else if imageReference.ID == nil && (imageReference.Offer == nil || imageReference.Publisher == nil || imageReference.Sku == nil || imageReference.Version == nil) {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): Properties version, offer, publish and sku are mandatory when not using a custom image", poolName, resourceGroup)
}
} else {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): image reference property can not be empty", poolName, resourceGroup)
}
if startTaskValue, startTaskOk := d.GetOk("start_task"); startTaskOk {
startTaskList := startTaskValue.([]interface{})
startTask, startTaskErr := azure.ExpandBatchPoolStartTask(startTaskList)
if startTaskErr != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, startTaskErr)
}
// start task should have a user identity defined
userIdentity := startTask.UserIdentity
if userIdentityError := validateUserIdentity(userIdentity); userIdentityError != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, userIdentityError)
}
parameters.PoolProperties.StartTask = startTask
}
containerConfigurationSet := d.Get("container_configuration").([]interface{})
containerConfiguration, err := azure.ExpandBatchPoolContainerConfiguration(containerConfigurationSet)
if err != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
parameters.PoolProperties.DeploymentConfiguration = &batch.DeploymentConfiguration{
VirtualMachineConfiguration: &batch.VirtualMachineConfiguration{
NodeAgentSkuID: &nodeAgentSkuID,
ImageReference: imageReference,
ContainerConfiguration: containerConfiguration,
},
}
certificates := d.Get("certificate").([]interface{})
certificateReferences, err := azure.ExpandBatchPoolCertificateReferences(certificates)
if err != nil {
return fmt.Errorf("Error expanding `certificate`: %+v", err)
}
parameters.PoolProperties.Certificates = certificateReferences
if err := validateBatchPoolCrossFieldRules(¶meters); err != nil {
return err
}
future, err := client.Create(ctx, resourceGroup, accountName, poolName, parameters, "", "")
if err != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for creation of Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, accountName, poolName)
if err != nil {
return fmt.Errorf("Error retrieving Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Batch pool %q (resource group %q) ID", poolName, resourceGroup)
}
d.SetId(*read.ID)
// if the pool is not Steady after the create operation, wait for it to be Steady
if props := read.PoolProperties; props != nil && props.AllocationState != batch.Steady {
if err = waitForBatchPoolPendingResizeOperation(ctx, client, resourceGroup, accountName, poolName); err != nil {
return fmt.Errorf("Error waiting for Batch pool %q (resource group %q) being ready", poolName, resourceGroup)
}
}
return resourceArmBatchPoolRead(d, meta)
}
func resourceArmBatchPoolUpdate(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).batch.PoolClient
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
poolName := id.Path["pools"]
accountName := id.Path["batchAccounts"]
resp, err := client.Get(ctx, resourceGroup, accountName, poolName)
if err != nil {
return fmt.Errorf("Error retrieving the Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
if resp.PoolProperties.AllocationState != batch.Steady {
log.Printf("[INFO] there is a pending resize operation on this pool...")
stopPendingResizeOperation := d.Get("stop_pending_resize_operation").(bool)
if !stopPendingResizeOperation {
return fmt.Errorf("Error updating the Batch pool %q (Resource Group %q) because of pending resize operation. Set flag `stop_pending_resize_operation` to true to force update", poolName, resourceGroup)
}
log.Printf("[INFO] stopping the pending resize operation on this pool...")
if _, err = client.StopResize(ctx, resourceGroup, accountName, poolName); err != nil {
return fmt.Errorf("Error stopping resize operation for Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
// waiting for the pool to be in steady state
if err = waitForBatchPoolPendingResizeOperation(ctx, client, resourceGroup, accountName, poolName); err != nil {
return fmt.Errorf("Error waiting for Batch pool %q (resource group %q) being ready", poolName, resourceGroup)
}
}
parameters := batch.Pool{
PoolProperties: &batch.PoolProperties{},
}
scaleSettings, err := expandBatchPoolScaleSettings(d)
if err != nil {
return fmt.Errorf("Error expanding scale settings: %+v", err)
}
parameters.PoolProperties.ScaleSettings = scaleSettings
if startTaskValue, startTaskOk := d.GetOk("start_task"); startTaskOk {
startTaskList := startTaskValue.([]interface{})
startTask, startTaskErr := azure.ExpandBatchPoolStartTask(startTaskList)
if startTaskErr != nil {
return fmt.Errorf("Error updating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, startTaskErr)
}
// start task should have a user identity defined
userIdentity := startTask.UserIdentity
if userIdentityError := validateUserIdentity(userIdentity); userIdentityError != nil {
return fmt.Errorf("Error creating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, userIdentityError)
}
parameters.PoolProperties.StartTask = startTask
}
certificates := d.Get("certificate").([]interface{})
certificateReferences, err := azure.ExpandBatchPoolCertificateReferences(certificates)
if err != nil {
return fmt.Errorf("Error expanding `certificate`: %+v", err)
}
parameters.PoolProperties.Certificates = certificateReferences
if err := validateBatchPoolCrossFieldRules(¶meters); err != nil {
return err
}
result, err := client.Update(ctx, resourceGroup, accountName, poolName, parameters, "")
if err != nil {
return fmt.Errorf("Error updating Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
// if the pool is not Steady after the update, wait for it to be Steady
if props := result.PoolProperties; props != nil && props.AllocationState != batch.Steady {
if err := waitForBatchPoolPendingResizeOperation(ctx, client, resourceGroup, accountName, poolName); err != nil {
return fmt.Errorf("Error waiting for Batch pool %q (resource group %q) being ready", poolName, resourceGroup)
}
}
return resourceArmBatchPoolRead(d, meta)
}
func resourceArmBatchPoolRead(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).batch.PoolClient
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
poolName := id.Path["pools"]
accountName := id.Path["batchAccounts"]
resp, err := client.Get(ctx, resourceGroup, accountName, poolName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Error: Batch pool %q in account %q (Resource Group %q) was not found", poolName, accountName, resourceGroup)
}
return fmt.Errorf("Error making Read request on AzureRM Batch pool %q: %+v", poolName, err)
}
d.Set("name", poolName)
d.Set("account_name", accountName)
d.Set("resource_group_name", resourceGroup)
if props := resp.PoolProperties; props != nil {
d.Set("vm_size", props.VMSize)
if scaleSettings := props.ScaleSettings; scaleSettings != nil {
if err := d.Set("auto_scale", azure.FlattenBatchPoolAutoScaleSettings(scaleSettings.AutoScale)); err != nil {
return fmt.Errorf("Error flattening `auto_scale`: %+v", err)
}
if err := d.Set("fixed_scale", azure.FlattenBatchPoolFixedScaleSettings(scaleSettings.FixedScale)); err != nil {
return fmt.Errorf("Error flattening `fixed_scale `: %+v", err)
}
}
if props.DeploymentConfiguration != nil &&
props.DeploymentConfiguration.VirtualMachineConfiguration != nil &&
props.DeploymentConfiguration.VirtualMachineConfiguration.ImageReference != nil {
imageReference := props.DeploymentConfiguration.VirtualMachineConfiguration.ImageReference
d.Set("storage_image_reference", azure.FlattenBatchPoolImageReference(imageReference))
d.Set("node_agent_sku_id", props.DeploymentConfiguration.VirtualMachineConfiguration.NodeAgentSkuID)
}
if dcfg := props.DeploymentConfiguration; dcfg != nil {
if vmcfg := dcfg.VirtualMachineConfiguration; vmcfg != nil {
d.Set("container_configuration", azure.FlattenBatchPoolContainerConfiguration(d, vmcfg.ContainerConfiguration))
}
}
if err := d.Set("certificate", azure.FlattenBatchPoolCertificateReferences(props.Certificates)); err != nil {
return fmt.Errorf("Error flattening `certificate`: %+v", err)
}
d.Set("start_task", azure.FlattenBatchPoolStartTask(props.StartTask))
}
return nil
}
func resourceArmBatchPoolDelete(d *schema.ResourceData, meta interface{}) error {
ctx := meta.(*ArmClient).StopContext
client := meta.(*ArmClient).batch.PoolClient
id, err := azure.ParseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
poolName := id.Path["pools"]
accountName := id.Path["batchAccounts"]
future, err := client.Delete(ctx, resourceGroup, accountName, poolName)
if err != nil {
return fmt.Errorf("Error deleting Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error waiting for deletion of Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
}
return nil
}
func expandBatchPoolScaleSettings(d *schema.ResourceData) (*batch.ScaleSettings, error) {
scaleSettings := &batch.ScaleSettings{}
autoScaleValue, autoScaleOk := d.GetOk("auto_scale")
fixedScaleValue, fixedScaleOk := d.GetOk("fixed_scale")
if !autoScaleOk && !fixedScaleOk {
return nil, fmt.Errorf("Error: auto_scale block or fixed_scale block need to be specified")
}
if autoScaleOk && fixedScaleOk {
return nil, fmt.Errorf("Error: auto_scale and fixed_scale blocks cannot be specified at the same time")
}
if autoScaleOk {
autoScale := autoScaleValue.([]interface{})
if len(autoScale) == 0 {
return nil, fmt.Errorf("Error: when scale mode is Auto, auto_scale block is required")
}
autoScaleSettings := autoScale[0].(map[string]interface{})
autoScaleEvaluationInterval := autoScaleSettings["evaluation_interval"].(string)
autoScaleFormula := autoScaleSettings["formula"].(string)
scaleSettings.AutoScale = &batch.AutoScaleSettings{
EvaluationInterval: &autoScaleEvaluationInterval,
Formula: &autoScaleFormula,
}
} else if fixedScaleOk {
fixedScale := fixedScaleValue.([]interface{})
if len(fixedScale) == 0 {
return nil, fmt.Errorf("Error: when scale mode is Fixed, fixed_scale block is required")
}
fixedScaleSettings := fixedScale[0].(map[string]interface{})
targetDedicatedNodes := int32(fixedScaleSettings["target_dedicated_nodes"].(int))
targetLowPriorityNodes := int32(fixedScaleSettings["target_low_priority_nodes"].(int))
resizeTimeout := fixedScaleSettings["resize_timeout"].(string)
scaleSettings.FixedScale = &batch.FixedScaleSettings{
ResizeTimeout: &resizeTimeout,
TargetDedicatedNodes: &targetDedicatedNodes,
TargetLowPriorityNodes: &targetLowPriorityNodes,
}
}
return scaleSettings, nil
}
func waitForBatchPoolPendingResizeOperation(ctx context.Context, client *batch.PoolClient, resourceGroup string, accountName string, poolName string) error {
// waiting for the pool to be in steady state
log.Printf("[INFO] waiting for the pending resize operation on this pool to be stopped...")
isSteady := false
for !isSteady {
resp, err := client.Get(ctx, resourceGroup, accountName, poolName)
if err != nil {
return fmt.Errorf("Error retrieving the Batch pool %q (Resource Group %q): %+v", poolName, resourceGroup, err)
}
isSteady = resp.PoolProperties.AllocationState == batch.Steady
time.Sleep(time.Second * 30)
log.Printf("[INFO] waiting for the pending resize operation on this pool to be stopped... New try in 30 seconds...")
}
return nil
}
// validateUserIdentity validates that the user identity for a start task has been well specified
// it should have a auto_user block or a user_name defined, but not both at the same time.
func validateUserIdentity(userIdentity *batch.UserIdentity) error {
if userIdentity == nil {
return errors.New("user_identity block needs to be specified")
}
if userIdentity.AutoUser == nil && userIdentity.UserName == nil {
return errors.New("auto_user or user_name needs to be specified in the user_identity block")
}
if userIdentity.AutoUser != nil && userIdentity.UserName != nil {
return errors.New("auto_user and user_name cannot be specified in the user_identity at the same time")
}
return nil
}
func validateBatchPoolCrossFieldRules(pool *batch.Pool) error {
// Perform validation across multiple fields as per https://docs.microsoft.com/en-us/rest/api/batchmanagement/pool/create#resourcefile
if pool.StartTask != nil {
startTask := *pool.StartTask
if startTask.ResourceFiles != nil {
for _, referenceFile := range *startTask.ResourceFiles {
// Must specify exactly one of AutoStorageContainerName, StorageContainerUrl or HttpUrl
sourceCount := 0
if referenceFile.AutoStorageContainerName != nil {
sourceCount++
}
if referenceFile.StorageContainerURL != nil {
sourceCount++
}
if referenceFile.HTTPURL != nil {
sourceCount++
}
if sourceCount != 1 {
return fmt.Errorf("Exactly one of auto_storage_container_name, storage_container_url and http_url must be specified")
}
if referenceFile.BlobPrefix != nil {
if referenceFile.AutoStorageContainerName == nil && referenceFile.StorageContainerURL == nil {
return fmt.Errorf("auto_storage_container_name or storage_container_url must be specified when using blob_prefix")
}
}
if referenceFile.HTTPURL != nil {
if referenceFile.FilePath == nil {
return fmt.Errorf("file_path must be specified when using http_url")
}
}
}
}
}
return nil
}