-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
managed-compute-environment.ts
1210 lines (1072 loc) · 44.6 KB
/
managed-compute-environment.ts
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
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as eks from 'aws-cdk-lib/aws-eks';
import * as iam from 'aws-cdk-lib/aws-iam';
import { IRole } from 'aws-cdk-lib/aws-iam';
import { ArnFormat, Duration, ITaggable, Lazy, Resource, Stack, TagManager, TagType } from 'aws-cdk-lib/core';
import { Construct } from 'constructs';
import { CfnComputeEnvironment } from 'aws-cdk-lib/aws-batch';
import { IComputeEnvironment, ComputeEnvironmentBase, ComputeEnvironmentProps } from './compute-environment-base';
/**
* Represents a Managed ComputeEnvironment. Batch will provision EC2 Instances to
* meet the requirements of the jobs executing in this ComputeEnvironment.
*/
export interface IManagedComputeEnvironment extends IComputeEnvironment, ec2.IConnectable, ITaggable {
/**
* The maximum vCpus this `ManagedComputeEnvironment` can scale up to.
*
* *Note*: if this Compute Environment uses EC2 resources (not Fargate) with either `AllocationStrategy.BEST_FIT_PROGRESSIVE` or
* `AllocationStrategy.SPOT_CAPACITY_OPTIMIZED`, or `AllocationStrategy.BEST_FIT` with Spot instances,
* The scheduler may exceed this number by at most one of the instances specified in `instanceTypes`
* or `instanceClasses`.
*/
readonly maxvCpus: number;
/**
* Specifies whether this Compute Environment is replaced if an update is made that requires
* replacing its instances. To enable more properties to be updated,
* set this property to `false`. When changing the value of this property to false,
* do not change any other properties at the same time.
* If other properties are changed at the same time,
* and the change needs to be rolled back but it can't,
* it's possible for the stack to go into the UPDATE_ROLLBACK_FAILED state.
* You can't update a stack that is in the UPDATE_ROLLBACK_FAILED state.
* However, if you can continue to roll it back,
* you can return the stack to its original settings and then try to update it again.
*
* The properties which require a replacement of the Compute Environment are:
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-replacecomputeenvironment
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-continueupdaterollback.html
*/
readonly replaceComputeEnvironment?: boolean;
/**
* Whether or not to use spot instances.
* Spot instances are less expensive EC2 instances that can be
* reclaimed by EC2 at any time; your job will be given two minutes
* of notice before reclamation.
*
* @default false
*/
readonly spot?: boolean;
/**
* Only meaningful if `terminateOnUpdate` is `false`. If so,
* when an infrastructure update is triggered, any running jobs
* will be allowed to run until `updateTimeout` has expired.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/updating-compute-environments.html
* @default 30 minutes
*/
readonly updateTimeout?: Duration;
/**
* Whether or not any running jobs will be immediately terminated when an infrastructure update
* occurs. If this is enabled, any terminated jobs may be retried, depending on the job's
* retry policy.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/updating-compute-environments.html
*
* @default false
*/
readonly terminateOnUpdate?: boolean;
/**
* The security groups this Compute Environment will launch instances in.
*/
readonly securityGroups: ec2.ISecurityGroup[];
/**
* The VPC Subnets this Compute Environment will launch instances in.
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* Whether or not the AMI is updated to the latest one supported by Batch
* when an infrastructure update occurs.
*
* If you specify a specific AMI, this property will be ignored.
*
* @default true
*/
readonly updateToLatestImageVersion?: boolean;
}
/**
* Props for a ManagedComputeEnvironment
*/
export interface ManagedComputeEnvironmentProps extends ComputeEnvironmentProps {
/**
* The maximum vCpus this `ManagedComputeEnvironment` can scale up to.
* Each vCPU is equivalent to 1024 CPU shares.
*
* *Note*: if this Compute Environment uses EC2 resources (not Fargate) with either `AllocationStrategy.BEST_FIT_PROGRESSIVE` or
* `AllocationStrategy.SPOT_CAPACITY_OPTIMIZED`, or `AllocationStrategy.BEST_FIT` with Spot instances,
* The scheduler may exceed this number by at most one of the instances specified in `instanceTypes`
* or `instanceClasses`.
*
* @default 256
*/
readonly maxvCpus?: number;
/**
* Specifies whether this Compute Environment is replaced if an update is made that requires
* replacing its instances. To enable more properties to be updated,
* set this property to `false`. When changing the value of this property to false,
* do not change any other properties at the same time.
* If other properties are changed at the same time,
* and the change needs to be rolled back but it can't,
* it's possible for the stack to go into the UPDATE_ROLLBACK_FAILED state.
* You can't update a stack that is in the UPDATE_ROLLBACK_FAILED state.
* However, if you can continue to roll it back,
* you can return the stack to its original settings and then try to update it again.
*
* The properties which require a replacement of the Compute Environment are:
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-replacecomputeenvironment
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-continueupdaterollback.html
*
* @default false
*/
readonly replaceComputeEnvironment?: boolean;
/**
* Whether or not to use spot instances.
* Spot instances are less expensive EC2 instances that can be
* reclaimed by EC2 at any time; your job will be given two minutes
* of notice before reclamation.
*
* @default false
*/
readonly spot?: boolean;
/**
* Only meaningful if `terminateOnUpdate` is `false`. If so,
* when an infrastructure update is triggered, any running jobs
* will be allowed to run until `updateTimeout` has expired.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/updating-compute-environments.html
*
* @default 30 minutes
*/
readonly updateTimeout?: Duration;
/**
* Whether or not any running jobs will be immediately terminated when an infrastructure update
* occurs. If this is enabled, any terminated jobs may be retried, depending on the job's
* retry policy.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/updating-compute-environments.html
*
* @default false
*/
readonly terminateOnUpdate?: boolean;
/**
* VPC in which this Compute Environment will launch Instances
*/
readonly vpc: ec2.IVpc;
/**
* The security groups this Compute Environment will launch instances in.
*
* @default new security groups will be created
*/
readonly securityGroups?: ec2.ISecurityGroup[];
/**
* The VPC Subnets this Compute Environment will launch instances in.
*
* @default new subnets will be created
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* Whether or not the AMI is updated to the latest one supported by Batch
* when an infrastructure update occurs.
*
* If you specify a specific AMI, this property will be ignored.
*
* @default true
*/
readonly updateToLatestImageVersion?: boolean;
}
/**
* Abstract base class for ManagedComputeEnvironments
* @internal
*/
export abstract class ManagedComputeEnvironmentBase extends ComputeEnvironmentBase implements IManagedComputeEnvironment {
public readonly maxvCpus: number;
public readonly replaceComputeEnvironment?: boolean;
public readonly spot?: boolean;
public readonly updateTimeout?: Duration;
public readonly terminateOnUpdate?: boolean;
public readonly securityGroups: ec2.ISecurityGroup[];
public readonly updateToLatestImageVersion?: boolean;
public readonly tags: TagManager = new TagManager(TagType.MAP, 'AWS::Batch::ComputeEnvironment');
public readonly connections: ec2.Connections;
constructor(scope: Construct, id: string, props: ManagedComputeEnvironmentProps) {
super(scope, id, props);
this.maxvCpus = props.maxvCpus ?? DEFAULT_MAX_VCPUS;
this.replaceComputeEnvironment = props.replaceComputeEnvironment ?? false;
this.spot = props.spot;
this.updateTimeout = props.updateTimeout;
this.terminateOnUpdate = props.terminateOnUpdate;
this.updateToLatestImageVersion = props.updateToLatestImageVersion ?? true;
this.securityGroups = props.securityGroups ?? [
new ec2.SecurityGroup(this, 'SecurityGroup', {
vpc: props.vpc,
}),
];
this.connections = new ec2.Connections({
securityGroups: this.securityGroups,
});
}
}
/**
* A ManagedComputeEnvironment that uses ECS orchestration on EC2 instances.
*/
export interface IManagedEc2EcsComputeEnvironment extends IManagedComputeEnvironment {
/**
* Configure which AMIs this Compute Environment can launch.
*
* Leave this `undefined` to allow Batch to choose the latest AMIs it supports for each instance that it launches.
*
* @default
* - ECS_AL2 compatible AMI ids for non-GPU instances, ECS_AL2_NVIDIA compatible AMI ids for GPU instances
*/
readonly images?: EcsMachineImage[];
/**
* The allocation strategy to use if not enough instances of
* the best fitting instance type can be allocated.
*
* @default - `BEST_FIT_PROGRESSIVE` if not using Spot instances,
* `SPOT_CAPACITY_OPTIMIZED` if using Spot instances.
*/
readonly allocationStrategy?: AllocationStrategy;
/**
* The maximum percentage that a Spot Instance price can be when compared with the
* On-Demand price for that instance type before instances are launched.
* For example, if your maximum percentage is 20%, the Spot price must be
* less than 20% of the current On-Demand price for that Instance.
* You always pay the lowest market price and never more than your maximum percentage.
* For most use cases, Batch recommends leaving this field empty.
*
* @default - 100%
*/
readonly spotBidPercentage?: number;
/**
* The service-linked role that Spot Fleet needs to launch instances on your behalf.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/spot_fleet_IAM_role.html
*
* @default - a new Role will be created
*/
readonly spotFleetRole?: iam.IRole;
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
*/
readonly instanceTypes: ec2.InstanceType[];
/**
* The instance classes that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
* Batch will automatically choose the size.
*/
readonly instanceClasses: ec2.InstanceClass[];
/**
* Whether or not to use batch's optimal instance type.
* The optimal instance type is equivalent to adding the
* C4, M4, and R4 instance classes. You can specify other instance classes
* (of the same architecture) in addition to the optimal instance classes.
*
* @default true
*/
readonly useOptimalInstanceClasses?: boolean;
/**
* The execution Role that instances launched by this Compute Environment will use.
*
* @default - a role will be created
*/
readonly instanceRole?: iam.IRole;
/**
* The Launch Template that this Compute Environment
* will use to provision EC2 Instances.
*
* *Note*: if `securityGroups` is specified on both your
* launch template and this Compute Environment, **the
* `securityGroup`s on the Compute Environment override the
* ones on the launch template.
*
* @default no launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* The minimum vCPUs that an environment should maintain,
* even if the compute environment is DISABLED.
*
* @default 0
*/
readonly minvCpus?: number;
/**
* The EC2 placement group to associate with your compute resources.
* If you intend to submit multi-node parallel jobs to this Compute Environment,
* you should consider creating a cluster placement group and associate it with your compute resources.
* This keeps your multi-node parallel job on a logical grouping of instances
* within a single Availability Zone with high network flow potential.
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html
*
* @default - no placement group
*/
readonly placementGroup?: ec2.IPlacementGroup;
/**
* Add an instance type to this compute environment
*/
addInstanceType(instanceType: ec2.InstanceType): void;
/**
* Add an instance class to this compute environment
*/
addInstanceClass(instanceClass: ec2.InstanceClass): void;
}
/**
* Base interface for containing all information needed to
* configure a MachineImage in Batch
*/
interface MachineImage {
/**
* The machine image to use
*
* @default - chosen by batch
*/
readonly image?: ec2.IMachineImage;
}
/**
* A Batch MachineImage that is compatible with ECS
*/
export interface EcsMachineImage extends MachineImage {
/**
* Tells Batch which instance type to launch this image on
*
* @default - 'ECS_AL2' for non-gpu instances, 'ECS_AL2_NVIDIA' for gpu instances
*/
readonly imageType?: EcsMachineImageType;
}
/**
* A Batch MachineImage that is compatible with EKS
*/
export interface EksMachineImage extends MachineImage{
/**
* Tells Batch which instance type to launch this image on
*
* @default - 'EKS_AL2' for non-gpu instances, 'EKS_AL2_NVIDIA' for gpu instances
*/
readonly imageType?: EksMachineImageType;
}
/**
* Maps the image to instance types
*/
export enum EcsMachineImageType {
/**
* Tells Batch that this machine image runs on non-GPU instances
*/
ECS_AL2 = 'ECS_AL2',
/**
* Tells Batch that this machine image runs on GPU instances
*/
ECS_AL2_NVIDIA = 'ECS_AL2_NVIDIA',
}
/**
* Maps the image to instance types
*/
export enum EksMachineImageType {
/**
* Tells Batch that this machine image runs on non-GPU instances
*/
EKS_AL2 = 'EKS_AL2',
/**
* Tells Batch that this machine image runs on GPU instances
*/
EKS_AL2_NVIDIA = 'EKS_AL2_NVIDIA',
}
/**
* Determines how this compute environment chooses instances to spawn
*
* @see https://aws.amazon.com/blogs/compute/optimizing-for-cost-availability-and-throughput-by-selecting-your-aws-batch-allocation-strategy/
*/
export enum AllocationStrategy {
/**
* Batch chooses the lowest-cost instance type that fits all the jobs in the queue.
* If instances of that type are not available, the queue will not choose a new type;
* instead, it will wait for the instance to become available.
* This can stall your `Queue`, with your compute environment only using part of its max capacity
* (or none at all) until the `BEST_FIT` instance becomes available.
* This allocation strategy keeps costs lower but can limit scaling.
* `BEST_FIT` isn't supported when updating compute environments
*/
BEST_FIT = 'BEST_FIT',
/**
* This is the default Allocation Strategy if `spot` is `false` or unspecified.
* This strategy will examine the Jobs in the queue and choose whichever instance type meets the requirements
* of the jobs in the queue and with the lowest cost per vCPU, just as `BEST_FIT`.
* However, if not all of the capacity can be filled with this instance type,
* it will choose a new next-best instance type to run any jobs that couldn’t fit into the `BEST_FIT` capacity.
* To make the most use of this allocation strategy,
* it is recommended to use as many instance classes as is feasible for your workload.
*/
BEST_FIT_PROGRESSIVE = 'BEST_FIT_PROGRESSIVE',
/**
* If your workflow tolerates interruptions, you should enable `spot` on your `ComputeEnvironment`
* and use `SPOT_CAPACITY_OPTIMIZED` (this is the default if `spot` is enabled).
* This will tell Batch to choose the instance types from the ones you’ve specified that have
* the most spot capacity available to minimize the chance of interruption.
* To get the most benefit from your spot instances,
* you should allow Batch to choose from as many different instance types as possible.
*/
SPOT_CAPACITY_OPTIMIZED = 'SPOT_CAPACITY_OPTIMIZED',
}
/**
* Props for a ManagedEc2EcsComputeEnvironment
*/
export interface ManagedEc2EcsComputeEnvironmentProps extends ManagedComputeEnvironmentProps {
/**
* Whether or not to use batch's optimal instance type.
* The optimal instance type is equivalent to adding the
* C4, M4, and R4 instance classes. You can specify other instance classes
* (of the same architecture) in addition to the optimal instance classes.
*
* @default true
*/
readonly useOptimalInstanceClasses?: boolean;
/**
* Configure which AMIs this Compute Environment can launch.
* If you specify this property with only `image` specified, then the
* `imageType` will default to `ECS_AL2`. *If your image needs GPU resources,
* specify `ECS_AL2_NVIDIA`; otherwise, the instances will not be able to properly
* join the ComputeEnvironment*.
*
* @default
* - ECS_AL2 for non-GPU instances, ECS_AL2_NVIDIA for GPU instances
*/
readonly images?: EcsMachineImage[];
/**
* The allocation strategy to use if not enough instances of
* the best fitting instance type can be allocated.
*
* @default - `BEST_FIT_PROGRESSIVE` if not using Spot instances,
* `SPOT_CAPACITY_OPTIMIZED` if using Spot instances.
*/
readonly allocationStrategy?: AllocationStrategy;
/**
* The maximum percentage that a Spot Instance price can be when compared with the
* On-Demand price for that instance type before instances are launched.
* For example, if your maximum percentage is 20%, the Spot price must be
* less than 20% of the current On-Demand price for that Instance.
* You always pay the lowest market price and never more than your maximum percentage.
* For most use cases, Batch recommends leaving this field empty.
*
* Implies `spot == true` if set
*
* @default 100%
*/
readonly spotBidPercentage?: number;
/**
* The service-linked role that Spot Fleet needs to launch instances on your behalf.
*
* @see https://docs.aws.amazon.com/batch/latest/userguide/spot_fleet_IAM_role.html
*
* @default - a new role will be created
*/
readonly spotFleetRole?: iam.IRole;
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
*
* @default - the instances Batch considers will be used (currently C4, M4, and R4)
*/
readonly instanceTypes?: ec2.InstanceType[];
/**
* The instance classes that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
* Batch will automatically choose the instance size.
*
* @default - the instances Batch considers will be used (currently C4, M4, and R4)
*/
readonly instanceClasses?: ec2.InstanceClass[];
/**
* The execution Role that instances launched by this Compute Environment will use.
*
* @default - a role will be created
*/
readonly instanceRole?: iam.IRole;
/**
* The Launch Template that this Compute Environment
* will use to provision EC2 Instances.
*
* *Note*: if `securityGroups` is specified on both your
* launch template and this Compute Environment, **the
* `securityGroup`s on the Compute Environment override the
* ones on the launch template.
*
* @default no launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* The minimum vCPUs that an environment should maintain,
* even if the compute environment is DISABLED.
*
* @default 0
*/
readonly minvCpus?: number;
/**
* The EC2 placement group to associate with your compute resources.
* If you intend to submit multi-node parallel jobs to this Compute Environment,
* you should consider creating a cluster placement group and associate it with your compute resources.
* This keeps your multi-node parallel job on a logical grouping of instances
* within a single Availability Zone with high network flow potential.
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html
*
* @default - no placement group
*/
readonly placementGroup?: ec2.IPlacementGroup;
}
/**
* A ManagedComputeEnvironment that uses ECS orchestration on EC2 instances.
*
* @resource AWS::Batch::ComputeEnvironment
*/
export class ManagedEc2EcsComputeEnvironment extends ManagedComputeEnvironmentBase implements IManagedEc2EcsComputeEnvironment {
/**
* refer to an existing ComputeEnvironment by its arn.
*/
public static fromManagedEc2EcsComputeEnvironmentArn(
scope: Construct, id: string, managedEc2EcsComputeEnvironmentArn: string,
): IManagedEc2EcsComputeEnvironment {
const stack = Stack.of(scope);
const computeEnvironmentName = stack.splitArn(managedEc2EcsComputeEnvironmentArn, ArnFormat.SLASH_RESOURCE_NAME).resourceName!;
class Import extends Resource implements IManagedEc2EcsComputeEnvironment {
public readonly computeEnvironmentArn = managedEc2EcsComputeEnvironmentArn;
public readonly computeEnvironmentName = computeEnvironmentName;
public readonly enabled = true;
public readonly instanceClasses = [];
public readonly instanceTypes = [];
public readonly maxvCpus = 1;
public readonly connections = { } as any;
public readonly securityGroups = [];
public readonly tags: TagManager = new TagManager(TagType.MAP, 'AWS::Batch::ComputeEnvironment');
public addInstanceClass(_instanceClass: ec2.InstanceClass): void {
throw new Error(`cannot add instance class to imported ComputeEnvironment '${id}'`);
}
public addInstanceType(_instanceType: ec2.InstanceType): void {
throw new Error(`cannot add instance type to imported ComputeEnvironment '${id}'`);
}
}
return new Import(scope, id);
}
public readonly computeEnvironmentArn: string;
public readonly computeEnvironmentName: string;
public readonly images?: EcsMachineImage[];
public readonly allocationStrategy?: AllocationStrategy;
public readonly spotBidPercentage?: number;
public readonly spotFleetRole?: iam.IRole;
public readonly instanceTypes: ec2.InstanceType[];
public readonly instanceClasses: ec2.InstanceClass[];
public readonly instanceRole?: iam.IRole;
public readonly launchTemplate?: ec2.ILaunchTemplate;
public readonly minvCpus?: number;
public readonly placementGroup?: ec2.IPlacementGroup;
private readonly instanceProfile: iam.CfnInstanceProfile;
constructor(scope: Construct, id: string, props: ManagedEc2EcsComputeEnvironmentProps) {
super(scope, id, props);
this.images = props.images;
this.allocationStrategy = determineAllocationStrategy(id, props.allocationStrategy, this.spot);
this.spotBidPercentage = props.spotBidPercentage;
this.spotFleetRole = props.spotFleetRole ?? (
this.spot && this.allocationStrategy === AllocationStrategy.BEST_FIT
? createSpotFleetRole(this)
: undefined
);
this.instanceTypes = props.instanceTypes ?? [];
this.instanceClasses = props.instanceClasses ?? [];
const { instanceRole, instanceProfile } = createInstanceRoleAndProfile(this, props.instanceRole);
this.instanceRole = instanceRole;
this.instanceProfile = instanceProfile;
this.launchTemplate = props.launchTemplate;
this.minvCpus = props.minvCpus ?? DEFAULT_MIN_VCPUS;
this.placementGroup = props.placementGroup;
validateVCpus(id, this.minvCpus, this.maxvCpus);
validateSpotConfig(id, this.spot, this.spotBidPercentage, this.spotFleetRole);
const { subnetIds } = props.vpc.selectSubnets(props.vpcSubnets);
const resource = new CfnComputeEnvironment(this, 'Resource', {
...baseManagedResourceProperties(this, subnetIds),
computeEnvironmentName: props.computeEnvironmentName,
computeResources: {
...baseManagedResourceProperties(this, subnetIds).computeResources as CfnComputeEnvironment.ComputeResourcesProperty,
minvCpus: this.minvCpus,
instanceRole: this.instanceProfile.attrArn, // this is not a typo; this property actually takes a profile, not a standard role
instanceTypes: Lazy.list({
produce: () => renderInstances(this.instanceTypes, this.instanceClasses, props.useOptimalInstanceClasses),
}),
type: this.spot ? 'SPOT' : 'EC2',
spotIamFleetRole: this.spotFleetRole?.roleArn,
allocationStrategy: this.allocationStrategy,
bidPercentage: this.spotBidPercentage,
launchTemplate: this.launchTemplate ? {
launchTemplateId: this.launchTemplate?.launchTemplateId,
} : undefined,
ec2Configuration: this.images?.map((image) => {
return {
imageIdOverride: image.image?.getImage(this).imageId,
imageType: image.imageType ?? EcsMachineImageType.ECS_AL2,
};
}),
placementGroup: this.placementGroup?.placementGroupName,
tags: this.tags.renderedTags as any,
},
});
this.computeEnvironmentName = this.getResourceNameAttribute(resource.ref);
this.computeEnvironmentArn = this.getResourceArnAttribute(resource.attrComputeEnvironmentArn, {
service: 'batch',
resource: 'compute-environment',
resourceName: this.physicalName,
});
this.node.addValidation({ validate: () => validateInstances(this.instanceTypes, this.instanceClasses, props.useOptimalInstanceClasses) });
}
public addInstanceType(instanceType: ec2.InstanceType): void {
this.instanceTypes.push(instanceType);
}
public addInstanceClass(instanceClass: ec2.InstanceClass): void {
this.instanceClasses.push(instanceClass);
}
}
/**
* A ManagedComputeEnvironment that uses EKS orchestration on EC2 instances.
*/
interface IManagedEc2EksComputeEnvironment extends IManagedComputeEnvironment {
/**
* The namespace of the Cluster
*
* Cannot be 'default', start with 'kube-', or be longer than 64 characters.
*
* @see https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/
*/
readonly kubernetesNamespace?: string;
/**
* The cluster that backs this Compute Environment. Required
* for Compute Environments running Kubernetes jobs.
*
* Please ensure that you have followed the steps at
*
* https://docs.aws.amazon.com/batch/latest/userguide/getting-started-eks.html
*
* before attempting to deploy a `ManagedEc2EksComputeEnvironment` that uses this cluster.
* If you do not follow the steps in the link, the deployment fail with a message that the
* compute environment did not stabilize.
*/
readonly eksCluster: eks.ICluster;
/**
* Configure which AMIs this Compute Environment can launch.
*
* @default
* EKS_AL2 for non-GPU instances, EKS_AL2_NVIDIA for GPU instances,
*/
readonly images?: EksMachineImage[];
/**
* The allocation strategy to use if not enough instances of
* the best fitting instance type can be allocated.
*
* @default - `BEST_FIT_PROGRESSIVE` if not using Spot instances,
* `SPOT_CAPACITY_OPTIMIZED` if using Spot instances.
*/
readonly allocationStrategy?: AllocationStrategy;
/**
* The maximum percentage that a Spot Instance price can be when compared with the
* On-Demand price for that instance type before instances are launched.
* For example, if your maximum percentage is 20%, the Spot price must be
* less than 20% of the current On-Demand price for that Instance.
* You always pay the lowest market price and never more than your maximum percentage.
* For most use cases, Batch recommends leaving this field empty.
*
* Implies `spot == true` if set
*
* @default - 100%
*/
readonly spotBidPercentage?: number;
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
*/
readonly instanceTypes: ec2.InstanceType[];
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
*/
readonly instanceClasses: ec2.InstanceClass[];
/**
* The execution Role that instances launched by this Compute Environment will use.
*
* @default - a role will be created
*/
readonly instanceRole?: iam.IRole;
/**
* The Launch Template that this Compute Environment
* will use to provision EC2 Instances.
*
* *Note*: if `securityGroups` is specified on both your
* launch template and this Compute Environment, **the
* `securityGroup`s on the Compute Environment override the
* ones on the launch template.
*
* @default - no launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* The minimum vCPUs that an environment should maintain,
* even if the compute environment is DISABLED.
*
* @default 0
*/
readonly minvCpus?: number;
/**
* The EC2 placement group to associate with your compute resources.
* If you intend to submit multi-node parallel jobs to this Compute Environment,
* you should consider creating a cluster placement group and associate it with your compute resources.
* This keeps your multi-node parallel job on a logical grouping of instances
* within a single Availability Zone with high network flow potential.
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html
*
* @default - no placement group
*/
readonly placementGroup?: ec2.IPlacementGroup;
/**
* Add an instance type to this compute environment
*/
addInstanceType(instanceType: ec2.InstanceType): void;
/**
* Add an instance class to this compute environment
*/
addInstanceClass(instanceClass: ec2.InstanceClass): void;
}
/**
* Props for a ManagedEc2EksComputeEnvironment
*/
export interface ManagedEc2EksComputeEnvironmentProps extends ManagedComputeEnvironmentProps {
/**
* The namespace of the Cluster
*/
readonly kubernetesNamespace: string;
/**
* The cluster that backs this Compute Environment. Required
* for Compute Environments running Kubernetes jobs.
*
* Please ensure that you have followed the steps at
*
* https://docs.aws.amazon.com/batch/latest/userguide/getting-started-eks.html
*
* before attempting to deploy a `ManagedEc2EksComputeEnvironment` that uses this cluster.
* If you do not follow the steps in the link, the deployment fail with a message that the
* compute environment did not stabilize.
*/
readonly eksCluster: eks.ICluster;
/**
* Whether or not to use batch's optimal instance type.
* The optimal instance type is equivalent to adding the
* C4, M4, and R4 instance classes. You can specify other instance classes
* (of the same architecture) in addition to the optimal instance classes.
*
* @default true
*/
readonly useOptimalInstanceClasses?: boolean;
/**
* Configure which AMIs this Compute Environment can launch.
*
* @default
* If `imageKubernetesVersion` is specified,
* - EKS_AL2 for non-GPU instances, EKS_AL2_NVIDIA for GPU instances,
* Otherwise,
* - ECS_AL2 for non-GPU instances, ECS_AL2_NVIDIA for GPU instances,
*/
readonly images?: EksMachineImage[];
/**
* The allocation strategy to use if not enough instances of
* the best fitting instance type can be allocated.
*
* @default - `BEST_FIT_PROGRESSIVE` if not using Spot instances,
* `SPOT_CAPACITY_OPTIMIZED` if using Spot instances.
*/
readonly allocationStrategy?: AllocationStrategy;
/**
* The maximum percentage that a Spot Instance price can be when compared with the
* On-Demand price for that instance type before instances are launched.
* For example, if your maximum percentage is 20%, the Spot price must be
* less than 20% of the current On-Demand price for that Instance.
* You always pay the lowest market price and never more than your maximum percentage.
* For most use cases, Batch recommends leaving this field empty.
*
* Implies `spot == true` if set
*
* @default - 100%
*/
readonly spotBidPercentage?: number;
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
*
* @default - the instances Batch considers will be used (currently C4, M4, and R4)
*/
readonly instanceTypes?: ec2.InstanceType[];
/**
* The instance types that this Compute Environment can launch.
* Which one is chosen depends on the `AllocationStrategy` used.
* Batch will automatically choose the instance size.
*
* @default - the instances Batch considers will be used (currently C4, M4, and R4)
*/
readonly instanceClasses?: ec2.InstanceClass[];
/**
* The execution Role that instances launched by this Compute Environment will use.
*
* @default - a role will be created
*/
readonly instanceRole?: iam.IRole;
/**
* The Launch Template that this Compute Environment
* will use to provision EC2 Instances.
*
* *Note*: if `securityGroups` is specified on both your
* launch template and this Compute Environment, **the
* `securityGroup`s on the Compute Environment override the
* ones on the launch template.**
*
* @default - no launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* The minimum vCPUs that an environment should maintain,
* even if the compute environment is DISABLED.
*
* @default 0
*/
readonly minvCpus?: number;
/**
* The EC2 placement group to associate with your compute resources.
* If you intend to submit multi-node parallel jobs to this Compute Environment,
* you should consider creating a cluster placement group and associate it with your compute resources.
* This keeps your multi-node parallel job on a logical grouping of instances
* within a single Availability Zone with high network flow potential.
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html
*
* @default - no placement group
*/
readonly placementGroup?: ec2.IPlacementGroup;
}
/**
* A ManagedComputeEnvironment that uses ECS orchestration on EC2 instances.
*
* @resource AWS::Batch::ComputeEnvironment
*/
export class ManagedEc2EksComputeEnvironment extends ManagedComputeEnvironmentBase implements IManagedEc2EksComputeEnvironment {
public readonly kubernetesNamespace?: string;
public readonly eksCluster: eks.ICluster;
public readonly computeEnvironmentName: string;
public readonly computeEnvironmentArn: string;
public readonly images?: EksMachineImage[];
public readonly allocationStrategy?: AllocationStrategy;
public readonly spotBidPercentage?: number;
public readonly instanceTypes: ec2.InstanceType[];
public readonly instanceClasses: ec2.InstanceClass[];
public readonly instanceRole?: iam.IRole;
public readonly launchTemplate?: ec2.ILaunchTemplate;
public readonly minvCpus?: number;
public readonly placementGroup?: ec2.IPlacementGroup;
private readonly instanceProfile: iam.CfnInstanceProfile;
constructor(scope: Construct, id: string, props: ManagedEc2EksComputeEnvironmentProps) {
super(scope, id, props);
this.kubernetesNamespace = props.kubernetesNamespace;
this.eksCluster = props.eksCluster;
this.images = props.images;
this.allocationStrategy = determineAllocationStrategy(id, props.allocationStrategy, this.spot);
if (this.allocationStrategy === AllocationStrategy.BEST_FIT) {
throw new Error(`ManagedEc2EksComputeEnvironment '${id}' uses invalid allocation strategy 'AllocationStrategy.BEST_FIT'`);
}
this.spotBidPercentage = props.spotBidPercentage;
this.instanceTypes = props.instanceTypes ?? [];
this.instanceClasses = props.instanceClasses ?? [];
const { instanceRole, instanceProfile } = createInstanceRoleAndProfile(this, props.instanceRole);
this.instanceRole = instanceRole;
this.instanceProfile = instanceProfile;
this.launchTemplate = props.launchTemplate;
this.minvCpus = props.minvCpus ?? DEFAULT_MIN_VCPUS;
this.placementGroup = props.placementGroup;
validateVCpus(id, this.minvCpus, this.maxvCpus);
validateSpotConfig(id, this.spot, this.spotBidPercentage);
const { subnetIds } = props.vpc.selectSubnets(props.vpcSubnets);
const resource = new CfnComputeEnvironment(this, 'Resource', {