-
Notifications
You must be signed in to change notification settings - Fork 4k
/
auto-scaling-group.ts
2540 lines (2256 loc) · 91.1 KB
/
auto-scaling-group.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 { Construct } from 'constructs';
import { AutoScalingGroupRequireImdsv2Aspect } from './aspects';
import { CfnAutoScalingGroup, CfnAutoScalingGroupProps, CfnLaunchConfiguration } from './autoscaling.generated';
import { BasicLifecycleHookProps, LifecycleHook } from './lifecycle-hook';
import { BasicScheduledActionProps, ScheduledAction } from './scheduled-action';
import { BasicStepScalingPolicyProps, StepScalingPolicy } from './step-scaling-policy';
import { BaseTargetTrackingProps, PredefinedMetric, TargetTrackingScalingPolicy } from './target-tracking-scaling-policy';
import { TerminationPolicy } from './termination-policy';
import { BlockDevice, BlockDeviceVolume, EbsDeviceVolumeType } from './volume';
import { WarmPool, WarmPoolOptions } from './warm-pool';
import * as cloudwatch from '../../aws-cloudwatch';
import * as ec2 from '../../aws-ec2';
import * as elb from '../../aws-elasticloadbalancing';
import * as elbv2 from '../../aws-elasticloadbalancingv2';
import * as iam from '../../aws-iam';
import * as sns from '../../aws-sns';
import {
Annotations,
Aspects,
Aws,
CfnAutoScalingRollingUpdate, CfnCreationPolicy, CfnUpdatePolicy,
Duration, FeatureFlags, Fn, IResource, Lazy, PhysicalName, Resource, Stack, Tags,
Token,
Tokenization, withResolved,
} from '../../core';
import { AUTOSCALING_GENERATE_LAUNCH_TEMPLATE } from '../../cx-api';
/**
* Name tag constant
*/
const NAME_TAG: string = 'Name';
/**
* The monitoring mode for instances launched in an autoscaling group
*/
export enum Monitoring {
/**
* Generates metrics every 5 minutes
*/
BASIC,
/**
* Generates metrics every minute
*/
DETAILED,
}
/**
* Basic properties of an AutoScalingGroup, except the exact machines to run and where they should run
*
* Constructs that want to create AutoScalingGroups can inherit
* this interface and specialize the essential parts in various ways.
*/
export interface CommonAutoScalingGroupProps {
/**
* Minimum number of instances in the fleet
*
* @default 1
*/
readonly minCapacity?: number;
/**
* Maximum number of instances in the fleet
*
* @default desiredCapacity
*/
readonly maxCapacity?: number;
/**
* Initial amount of instances in the fleet
*
* If this is set to a number, every deployment will reset the amount of
* instances to this number. It is recommended to leave this value blank.
*
* @default minCapacity, and leave unchanged during deployment
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-desiredcapacity
*/
readonly desiredCapacity?: number;
/**
* Name of SSH keypair to grant access to instances
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* You can either specify `keyPair` or `keyName`, not both.
*
* @default - No SSH access will be possible.
* @deprecated - Use `keyPair` instead - https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2-readme.html#using-an-existing-ec2-key-pair
*/
readonly keyName?: string;
/**
* The SSH keypair to grant access to the instance.
*
* Feature flag `AUTOSCALING_GENERATE_LAUNCH_TEMPLATE` must be enabled to use this property.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified.
*
* You can either specify `keyPair` or `keyName`, not both.
*
* @default - No SSH access will be possible.
*/
readonly keyPair?: ec2.IKeyPair;
/**
* Where to place instances within the VPC
*
* @default - All Private subnets.
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* SNS topic to send notifications about fleet changes
*
* @default - No fleet change notifications will be sent.
* @deprecated use `notifications`
*/
readonly notificationsTopic?: sns.ITopic;
/**
* Configure autoscaling group to send notifications about fleet changes to an SNS topic(s)
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-notificationconfigurations
* @default - No fleet change notifications will be sent.
*/
readonly notifications?: NotificationConfiguration[];
/**
* Whether the instances can initiate connections to anywhere by default
*
* @default true
*/
readonly allowAllOutbound?: boolean;
/**
* What to do when an AutoScalingGroup's instance configuration is changed
*
* This is applied when any of the settings on the ASG are changed that
* affect how the instances should be created (VPC, instance type, startup
* scripts, etc.). It indicates how the existing instances should be
* replaced with new instances matching the new config. By default,
* `updatePolicy` takes precedence over `updateType`.
*
* @default UpdateType.REPLACING_UPDATE, unless updatePolicy has been set
* @deprecated Use `updatePolicy` instead
*/
readonly updateType?: UpdateType;
/**
* Configuration for rolling updates
*
* Only used if updateType == UpdateType.RollingUpdate.
*
* @default - RollingUpdateConfiguration with defaults.
* @deprecated Use `updatePolicy` instead
*/
readonly rollingUpdateConfiguration?: RollingUpdateConfiguration;
/**
* Configuration for replacing updates.
*
* Only used if updateType == UpdateType.ReplacingUpdate. Specifies how
* many instances must signal success for the update to succeed.
*
* @default minSuccessfulInstancesPercent
* @deprecated Use `signals` instead
*/
readonly replacingUpdateMinSuccessfulInstancesPercent?: number;
/**
* If the ASG has scheduled actions, don't reset unchanged group sizes
*
* Only used if the ASG has scheduled actions (which may scale your ASG up
* or down regardless of cdk deployments). If true, the size of the group
* will only be reset if it has been changed in the CDK app. If false, the
* sizes will always be changed back to what they were in the CDK app
* on deployment.
*
* @default true
*/
readonly ignoreUnmodifiedSizeProperties?: boolean;
/**
* How many ResourceSignal calls CloudFormation expects before the resource is considered created
*
* @default 1 if resourceSignalTimeout is set, 0 otherwise
* @deprecated Use `signals` instead.
*/
readonly resourceSignalCount?: number;
/**
* The length of time to wait for the resourceSignalCount
*
* The maximum value is 43200 (12 hours).
*
* @default Duration.minutes(5) if resourceSignalCount is set, N/A otherwise
* @deprecated Use `signals` instead.
*/
readonly resourceSignalTimeout?: Duration;
/**
* Default scaling cooldown for this AutoScalingGroup
*
* @default Duration.minutes(5)
*/
readonly cooldown?: Duration;
/**
* Whether instances in the Auto Scaling Group should have public
* IP addresses associated with them.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default - Use subnet setting.
*/
readonly associatePublicIpAddress?: boolean;
/**
* The maximum hourly price (in USD) to be paid for any Spot Instance launched to fulfill the request. Spot Instances are
* launched when the price you specify exceeds the current Spot market price.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default none
*/
readonly spotPrice?: string;
/**
* Configuration for health checks
*
* @default - HealthCheck.ec2 with no grace period
*/
readonly healthCheck?: HealthCheck;
/**
* Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
*
* Each instance that is launched has an associated root device volume,
* either an Amazon EBS volume or an instance store volume.
* You can use block device mappings to specify additional EBS volumes or
* instance store volumes to attach to an instance when it is launched.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
*
* @default - Uses the block device mapping of the AMI
*/
readonly blockDevices?: BlockDevice[];
/**
* The maximum amount of time that an instance can be in service. The maximum duration applies
* to all current and future instances in the group. As an instance approaches its maximum duration,
* it is terminated and replaced, and cannot be used again.
*
* You must specify a value of at least 604,800 seconds (7 days). To clear a previously set value,
* leave this property undefined.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-max-instance-lifetime.html
*
* @default none
*/
readonly maxInstanceLifetime?: Duration;
/**
* Controls whether instances in this group are launched with detailed or basic monitoring.
*
* When detailed monitoring is enabled, Amazon CloudWatch generates metrics every minute and your account
* is charged a fee. When you disable detailed monitoring, CloudWatch generates metrics every 5 minutes.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @see https://docs.aws.amazon.com/autoscaling/latest/userguide/as-instance-monitoring.html#enable-as-instance-metrics
*
* @default - Monitoring.DETAILED
*/
readonly instanceMonitoring?: Monitoring;
/**
* Enable monitoring for group metrics, these metrics describe the group rather than any of its instances.
* To report all group metrics use `GroupMetrics.all()`
* Group metrics are reported in a granularity of 1 minute at no additional charge.
* @default - no group metrics will be reported
*
*/
readonly groupMetrics?: GroupMetrics[];
/**
* Configure waiting for signals during deployment
*
* Use this to pause the CloudFormation deployment to wait for the instances
* in the AutoScalingGroup to report successful startup during
* creation and updates. The UserData script needs to invoke `cfn-signal`
* with a success or failure code after it is done setting up the instance.
*
* Without waiting for signals, the CloudFormation deployment will proceed as
* soon as the AutoScalingGroup has been created or updated but before the
* instances in the group have been started.
*
* For example, to have instances wait for an Elastic Load Balancing health check before
* they signal success, add a health-check verification by using the
* cfn-init helper script. For an example, see the verify_instance_health
* command in the Auto Scaling rolling updates sample template:
*
* https://github.com/awslabs/aws-cloudformation-templates/blob/master/aws/services/AutoScaling/AutoScalingRollingUpdates.yaml
*
* @default - Do not wait for signals
*/
readonly signals?: Signals;
/**
* What to do when an AutoScalingGroup's instance configuration is changed
*
* This is applied when any of the settings on the ASG are changed that
* affect how the instances should be created (VPC, instance type, startup
* scripts, etc.). It indicates how the existing instances should be
* replaced with new instances matching the new config. By default, nothing
* is done and only new instances are launched with the new config.
*
* @default - `UpdatePolicy.rollingUpdate()` if using `init`, `UpdatePolicy.none()` otherwise
*/
readonly updatePolicy?: UpdatePolicy;
/**
* Whether newly-launched instances are protected from termination by Amazon
* EC2 Auto Scaling when scaling in.
*
* By default, Auto Scaling can terminate an instance at any time after launch
* when scaling in an Auto Scaling Group, subject to the group's termination
* policy. However, you may wish to protect newly-launched instances from
* being scaled in if they are going to run critical applications that should
* not be prematurely terminated.
*
* This flag must be enabled if the Auto Scaling Group will be associated with
* an ECS Capacity Provider with managed termination protection.
*
* @default false
*/
readonly newInstancesProtectedFromScaleIn?: boolean;
/**
* The name of the Auto Scaling group. This name must be unique per Region per account.
* @default - Auto generated by CloudFormation
*/
readonly autoScalingGroupName?: string;
/**
* A policy or a list of policies that are used to select the instances to
* terminate. The policies are executed in the order that you list them.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html
*
* @default - `TerminationPolicy.DEFAULT`
*/
readonly terminationPolicies?: TerminationPolicy[];
/**
* A lambda function Arn that can be used as a custom termination policy to select the instances
* to terminate. This property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION
* is used.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/lambda-custom-termination-policy.html
*
* @default - No lambda function Arn will be supplied
*/
readonly terminationPolicyCustomLambdaFunctionArn?: string;
/**
* The amount of time, in seconds, until a newly launched instance can contribute to the Amazon CloudWatch metrics.
* This delay lets an instance finish initializing before Amazon EC2 Auto Scaling aggregates instance metrics,
* resulting in more reliable usage data. Set this value equal to the amount of time that it takes for resource
* consumption to become stable after an instance reaches the InService state.
*
* To optimize the performance of scaling policies that scale continuously, such as target tracking and
* step scaling policies, we strongly recommend that you enable the default instance warmup, even if its value is set to 0 seconds
*
* Default instance warmup will not be added if no value is specified
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-default-instance-warmup.html
*
* @default None
*/
readonly defaultInstanceWarmup?: Duration;
/**
* Indicates whether Capacity Rebalancing is enabled. When you turn on Capacity Rebalancing, Amazon EC2 Auto Scaling
* attempts to launch a Spot Instance whenever Amazon EC2 notifies that a Spot Instance is at an elevated risk of
* interruption. After launching a new instance, it then terminates an old instance.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-capacityrebalance
*
* @default false
*
*/
readonly capacityRebalance?: boolean;
/**
* Add SSM session permissions to the instance role
*
* Setting this to `true` adds the necessary permissions to connect
* to the instance using SSM Session Manager. You can do this
* from the AWS Console.
*
* NOTE: Setting this flag to `true` may not be enough by itself.
* You must also use an AMI that comes with the SSM Agent, or install
* the SSM Agent yourself. See
* [Working with SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)
* in the SSM Developer Guide.
*
* @default false
*/
readonly ssmSessionPermissions?: boolean;
}
/**
* MixedInstancesPolicy allows you to configure a group that diversifies across On-Demand Instances
* and Spot Instances of multiple instance types. For more information, see Auto Scaling groups with
* multiple instance types and purchase options in the Amazon EC2 Auto Scaling User Guide:
*
* https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-purchase-options.html
*/
export interface MixedInstancesPolicy {
/**
* InstancesDistribution to use.
*
* @default - The value for each property in it uses a default value.
*/
readonly instancesDistribution?: InstancesDistribution;
/**
* Launch template to use.
*/
readonly launchTemplate: ec2.ILaunchTemplate;
/**
* Launch template overrides.
*
* The maximum number of instance types that can be associated with an Auto Scaling group is 40.
*
* The maximum number of distinct launch templates you can define for an Auto Scaling group is 20.
*
* @default - Do not provide any overrides
*/
readonly launchTemplateOverrides?: LaunchTemplateOverrides[];
}
/**
* Indicates how to allocate instance types to fulfill On-Demand capacity.
*/
export enum OnDemandAllocationStrategy {
/**
* This strategy uses the order of instance types in the LaunchTemplateOverrides to define the launch
* priority of each instance type. The first instance type in the array is prioritized higher than the
* last. If all your On-Demand capacity cannot be fulfilled using your highest priority instance, then
* the Auto Scaling group launches the remaining capacity using the second priority instance type, and
* so on.
*/
PRIORITIZED = 'prioritized',
/**
* This strategy uses the lowest-price instance types in each Availability Zone based on the current
* On-Demand instance price.
*
* To meet your desired capacity, you might receive On-Demand Instances of more than one instance type
* in each Availability Zone. This depends on how much capacity you request.
*/
LOWEST_PRICE = 'lowest-price',
}
/**
* Indicates how to allocate instance types to fulfill Spot capacity.
*/
export enum SpotAllocationStrategy {
/**
* The Auto Scaling group launches instances using the Spot pools with the lowest price, and evenly
* allocates your instances across the number of Spot pools that you specify.
*/
LOWEST_PRICE = 'lowest-price',
/**
* The Auto Scaling group launches instances using Spot pools that are optimally chosen based on the
* available Spot capacity.
*
* Recommended.
*/
CAPACITY_OPTIMIZED = 'capacity-optimized',
/**
* When you use this strategy, you need to set the order of instance types in the list of launch template
* overrides from highest to lowest priority (from first to last in the list). Amazon EC2 Auto Scaling
* honors the instance type priorities on a best-effort basis but optimizes for capacity first.
*/
CAPACITY_OPTIMIZED_PRIORITIZED = 'capacity-optimized-prioritized',
/**
* The price and capacity optimized allocation strategy looks at both price and
* capacity to select the Spot Instance pools that are the least likely to be
* interrupted and have the lowest possible price.
*/
PRICE_CAPACITY_OPTIMIZED = 'price-capacity-optimized',
}
/**
* InstancesDistribution is a subproperty of MixedInstancesPolicy that describes an instances distribution
* for an Auto Scaling group. The instances distribution specifies the distribution of On-Demand Instances
* and Spot Instances, the maximum price to pay for Spot Instances, and how the Auto Scaling group allocates
* instance types to fulfill On-Demand and Spot capacities.
*
* For more information and example configurations, see Auto Scaling groups with multiple instance types
* and purchase options in the Amazon EC2 Auto Scaling User Guide:
*
* https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-purchase-options.html
*/
export interface InstancesDistribution {
/**
* Indicates how to allocate instance types to fulfill On-Demand capacity. The only valid value is prioritized,
* which is also the default value.
*
* @default OnDemandAllocationStrategy.PRIORITIZED
*/
readonly onDemandAllocationStrategy?: OnDemandAllocationStrategy;
/**
* The minimum amount of the Auto Scaling group's capacity that must be fulfilled by On-Demand Instances. This
* base portion is provisioned first as your group scales. Defaults to 0 if not specified. If you specify weights
* for the instance types in the overrides, set the value of OnDemandBaseCapacity in terms of the number of
* capacity units, and not the number of instances.
*
* @default 0
*/
readonly onDemandBaseCapacity?: number;
/**
* Controls the percentages of On-Demand Instances and Spot Instances for your additional capacity beyond
* OnDemandBaseCapacity. Expressed as a number (for example, 20 specifies 20% On-Demand Instances, 80% Spot Instances).
* Defaults to 100 if not specified. If set to 100, only On-Demand Instances are provisioned.
*
* @default 100
*/
readonly onDemandPercentageAboveBaseCapacity?: number;
/**
* If the allocation strategy is lowest-price, the Auto Scaling group launches instances using the Spot pools with the
* lowest price, and evenly allocates your instances across the number of Spot pools that you specify. Defaults to
* lowest-price if not specified.
*
* If the allocation strategy is capacity-optimized (recommended), the Auto Scaling group launches instances using Spot
* pools that are optimally chosen based on the available Spot capacity. Alternatively, you can use capacity-optimized-prioritized
* and set the order of instance types in the list of launch template overrides from highest to lowest priority
* (from first to last in the list). Amazon EC2 Auto Scaling honors the instance type priorities on a best-effort basis but
* optimizes for capacity first.
*
* @default SpotAllocationStrategy.LOWEST_PRICE
*/
readonly spotAllocationStrategy?: SpotAllocationStrategy;
/**
* The number of Spot Instance pools to use to allocate your Spot capacity. The Spot pools are determined from the different instance
* types in the overrides. Valid only when the Spot allocation strategy is lowest-price. Value must be in the range of 1 to 20.
* Defaults to 2 if not specified.
*
* @default 2
*/
readonly spotInstancePools?: number;
/**
* The maximum price per unit hour that you are willing to pay for a Spot Instance. If you leave the value at its default (empty),
* Amazon EC2 Auto Scaling uses the On-Demand price as the maximum Spot price. To remove a value that you previously set, include
* the property but specify an empty string ("") for the value.
*
* @default "" - On-Demand price
*/
readonly spotMaxPrice?: string;
}
/**
* LaunchTemplateOverrides is a subproperty of LaunchTemplate that describes an override for a launch template.
*/
export interface LaunchTemplateOverrides {
/**
* The instance requirements. Amazon EC2 Auto Scaling uses your specified requirements to identify instance types.
* Then, it uses your On-Demand and Spot allocation strategies to launch instances from these instance types.
*
* You can specify up to four separate sets of instance requirements per Auto Scaling group.
* This is useful for provisioning instances from different Amazon Machine Images (AMIs) in the same Auto Scaling group.
* To do this, create the AMIs and create a new launch template for each AMI.
* Then, create a compatible set of instance requirements for each launch template.
*
* You must specify one of instanceRequirements or instanceType.
*
* @default - Do not override instance type
*/
readonly instanceRequirements?: CfnAutoScalingGroup.InstanceRequirementsProperty;
/**
* The instance type, such as m3.xlarge. You must use an instance type that is supported in your requested Region
* and Availability Zones.
*
* You must specify one of instanceRequirements or instanceType.
*
* @default - Do not override instance type
*/
readonly instanceType?: ec2.InstanceType;
/**
* Provides the launch template to be used when launching the instance type. For example, some instance types might
* require a launch template with a different AMI. If not provided, Amazon EC2 Auto Scaling uses the launch template
* that's defined for your mixed instances policy.
*
* @default - Do not override launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* The number of capacity units provided by the specified instance type in terms of virtual CPUs, memory, storage,
* throughput, or other relative performance characteristic. When a Spot or On-Demand Instance is provisioned, the
* capacity units count toward the desired capacity. Amazon EC2 Auto Scaling provisions instances until the desired
* capacity is totally fulfilled, even if this results in an overage. Value must be in the range of 1 to 999.
*
* For example, If there are 2 units remaining to fulfill capacity, and Amazon EC2 Auto Scaling can only provision
* an instance with a WeightedCapacity of 5 units, the instance is provisioned, and the desired capacity is exceeded
* by 3 units.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-weighting.html
*
* @default - Do not provide weight
*/
readonly weightedCapacity?: number;
}
/**
* Properties of a Fleet
*/
export interface AutoScalingGroupProps extends CommonAutoScalingGroupProps {
/**
* VPC to launch these instances in.
*/
readonly vpc: ec2.IVpc;
/**
* Launch template to use.
*
* Launch configuration related settings and MixedInstancesPolicy must not be specified when a
* launch template is specified.
*
* @default - Do not provide any launch template
*/
readonly launchTemplate?: ec2.ILaunchTemplate;
/**
* Mixed Instances Policy to use.
*
* Launch configuration related settings and Launch Template must not be specified when a
* MixedInstancesPolicy is specified.
*
* @default - Do not provide any MixedInstancesPolicy
*/
readonly mixedInstancesPolicy?: MixedInstancesPolicy;
/**
* Type of instance to launch
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default - Do not provide any instance type
*/
readonly instanceType?: ec2.InstanceType;
/**
* AMI to launch
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default - Do not provide any machine image
*/
readonly machineImage?: ec2.IMachineImage;
/**
* Security group to launch the instances in.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default - A SecurityGroup will be created if none is specified.
*/
readonly securityGroup?: ec2.ISecurityGroup;
/**
* Specific UserData to use
*
* The UserData may still be mutated after creation.
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @default - A UserData object appropriate for the MachineImage's
* Operating System is created.
*/
readonly userData?: ec2.UserData;
/**
* An IAM role to associate with the instance profile assigned to this Auto Scaling Group.
*
* The role must be assumable by the service principal `ec2.amazonaws.com`:
*
* `launchTemplate` and `mixedInstancesPolicy` must not be specified when this property is specified
*
* @example
*
* const role = new iam.Role(this, 'MyRole', {
* assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
* });
*
* @default A role will automatically be created, it can be accessed via the `role` property
*/
readonly role?: iam.IRole;
/**
* Apply the given CloudFormation Init configuration to the instances in the AutoScalingGroup at startup
*
* If you specify `init`, you must also specify `signals` to configure
* the number of instances to wait for and the timeout for waiting for the
* init process.
*
* @default - no CloudFormation init
*/
readonly init?: ec2.CloudFormationInit;
/**
* Use the given options for applying CloudFormation Init
*
* Describes the configsets to use and the timeout to wait
*
* @default - default options
*/
readonly initOptions?: ApplyCloudFormationInitOptions;
/**
* Whether IMDSv2 should be required on launched instances.
*
* @default false
*/
readonly requireImdsv2?: boolean;
/**
* Specifies the upper threshold as a percentage of the desired capacity of the Auto Scaling group.
* It represents the maximum percentage of the group that can be in service and healthy, or pending,
* to support your workload when replacing instances.
*
* Value range is 0 to 100. After it's set, both `minHealthyPercentage` and `maxHealthyPercentage` to
* -1 will clear the previously set value.
*
* Both or neither of `minHealthyPercentage` and `maxHealthyPercentage` must be specified, and the
* difference between them cannot be greater than 100. A large range increases the number of
* instances that can be replaced at the same time.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-instance-maintenance-policy.html
*
* @default - No instance maintenance policy.
*/
readonly maxHealthyPercentage?: number;
/**
* Specifies the lower threshold as a percentage of the desired capacity of the Auto Scaling group.
* It represents the minimum percentage of the group to keep in service, healthy, and ready to use
* to support your workload when replacing instances.
*
* Value range is 0 to 100. After it's set, both `minHealthyPercentage` and `maxHealthyPercentage` to
* -1 will clear the previously set value.
*
* Both or neither of `minHealthyPercentage` and `maxHealthyPercentage` must be specified, and the
* difference between them cannot be greater than 100. A large range increases the number of
* instances that can be replaced at the same time.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-instance-maintenance-policy.html
*
* @default - No instance maintenance policy.
*/
readonly minHealthyPercentage?: number;
}
/**
* Configure whether the AutoScalingGroup waits for signals
*
* If you do configure waiting for signals, you should make sure the instances
* invoke `cfn-signal` somewhere in their UserData to signal that they have
* started up (either successfully or unsuccessfully).
*
* Signals are used both during intial creation and subsequent updates.
*/
export abstract class Signals {
/**
* Wait for the desiredCapacity of the AutoScalingGroup amount of signals to have been received
*
* If no desiredCapacity has been configured, wait for minCapacity signals intead.
*
* This number is used during initial creation and during replacing updates.
* During rolling updates, all updated instances must send a signal.
*/
public static waitForAll(options: SignalsOptions = {}): Signals {
validatePercentage(options.minSuccessPercentage);
return new class extends Signals {
public renderCreationPolicy(renderOptions: RenderSignalsOptions): CfnCreationPolicy {
return this.doRender(options, renderOptions.desiredCapacity ?? renderOptions.minCapacity);
}
}();
}
/**
* Wait for the minCapacity of the AutoScalingGroup amount of signals to have been received
*
* This number is used during initial creation and during replacing updates.
* During rolling updates, all updated instances must send a signal.
*/
public static waitForMinCapacity(options: SignalsOptions = {}): Signals {
validatePercentage(options.minSuccessPercentage);
return new class extends Signals {
public renderCreationPolicy(renderOptions: RenderSignalsOptions): CfnCreationPolicy {
return this.doRender(options, renderOptions.minCapacity);
}
}();
}
/**
* Wait for a specific amount of signals to have been received
*
* You should send one signal per instance, so this represents the number of
* instances to wait for.
*
* This number is used during initial creation and during replacing updates.
* During rolling updates, all updated instances must send a signal.
*/
public static waitForCount(count: number, options: SignalsOptions = {}): Signals {
validatePercentage(options.minSuccessPercentage);
return new class extends Signals {
public renderCreationPolicy(): CfnCreationPolicy {
return this.doRender(options, count);
}
}();
}
/**
* Render the ASG's CreationPolicy
*/
public abstract renderCreationPolicy(renderOptions: RenderSignalsOptions): CfnCreationPolicy;
/**
* Helper to render the actual creation policy, as the logic between them is quite similar
*/
protected doRender(options: SignalsOptions, count?: number): CfnCreationPolicy {
const minSuccessfulInstancesPercent = validatePercentage(options.minSuccessPercentage);
return {
...options.minSuccessPercentage !== undefined ? { autoScalingCreationPolicy: { minSuccessfulInstancesPercent } } : { },
resourceSignal: {
count,
timeout: options.timeout?.toIsoString(),
},
};
}
}
/**
* Input for Signals.renderCreationPolicy
*/
export interface RenderSignalsOptions {
/**
* The desiredCapacity of the ASG
*
* @default - desired capacity not configured
*/
readonly desiredCapacity?: number;
/**
* The minSize of the ASG
*
* @default - minCapacity not configured
*/
readonly minCapacity?: number;
}
/**
* Customization options for Signal handling
*/
export interface SignalsOptions {
/**
* The percentage of signals that need to be successful
*
* If this number is less than 100, a percentage of signals may be failure
* signals while still succeeding the creation or update in CloudFormation.
*
* @default 100
*/
readonly minSuccessPercentage?: number;
/**
* How long to wait for the signals to be sent
*
* This should reflect how long it takes your instances to start up
* (including instance start time and instance initialization time).
*
* @default Duration.minutes(5)
*/
readonly timeout?: Duration;
}
/**
* How existing instances should be updated
*/
export abstract class UpdatePolicy {
/**
* Create a new AutoScalingGroup and switch over to it
*/
public static replacingUpdate(): UpdatePolicy {
return new class extends UpdatePolicy {
public _renderUpdatePolicy(): CfnUpdatePolicy {
return {
autoScalingReplacingUpdate: { willReplace: true },
};
}
}();
}
/**
* Replace the instances in the AutoScalingGroup one by one, or in batches
*/
public static rollingUpdate(options: RollingUpdateOptions = {}): UpdatePolicy {
const minSuccessPercentage = validatePercentage(options.minSuccessPercentage);
return new class extends UpdatePolicy {
public _renderUpdatePolicy(renderOptions: RenderUpdateOptions): CfnUpdatePolicy {
return {
autoScalingRollingUpdate: {
maxBatchSize: options.maxBatchSize,
minInstancesInService: options.minInstancesInService,
suspendProcesses: options.suspendProcesses ?? DEFAULT_SUSPEND_PROCESSES,
minSuccessfulInstancesPercent:
minSuccessPercentage ?? renderOptions.creationPolicy?.autoScalingCreationPolicy?.minSuccessfulInstancesPercent,
waitOnResourceSignals: options.waitOnResourceSignals ?? renderOptions.creationPolicy?.resourceSignal !== undefined ? true : undefined,
pauseTime: options.pauseTime?.toIsoString() ?? renderOptions.creationPolicy?.resourceSignal?.timeout,
},
};
}
}();
}
/**
* Render the ASG's CreationPolicy
* @internal
*/
public abstract _renderUpdatePolicy(renderOptions: RenderUpdateOptions): CfnUpdatePolicy;
}
/**
* Options for rendering UpdatePolicy
*/
interface RenderUpdateOptions {
/**
* The Creation Policy already created
*
* @default - no CreationPolicy configured
*/
readonly creationPolicy?: CfnCreationPolicy;
}
/**
* Options for customizing the rolling update
*/
export interface RollingUpdateOptions {
/**
* The maximum number of instances that AWS CloudFormation updates at once.
*
* This number affects the speed of the replacement.
*
* @default 1
*/
readonly maxBatchSize?: number;
/**
* The minimum number of instances that must be in service before more instances are replaced.
*
* This number affects the speed of the replacement.
*
* @default 0
*/
readonly minInstancesInService?: number;
/**
* Specifies the Auto Scaling processes to suspend during a stack update.
*
* Suspending processes prevents Auto Scaling from interfering with a stack
* update.
*
* @default HealthCheck, ReplaceUnhealthy, AZRebalance, AlarmNotification, ScheduledActions.
*/
readonly suspendProcesses?: ScalingProcess[];
/**
* Specifies whether the Auto Scaling group waits on signals from new instances during an update.
*
* @default true if you configured `signals` on the AutoScalingGroup, false otherwise
*/