91 types
This module is part of the AWS Cloud Development Kit project.
An AutoScalingGroup represents a number of instances on which you run your code. You
pick the size of the fleet, the instance type and the OS image:
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
# The latest Amazon Linux 2 image
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
})
Creating an AutoScalingGroup from a Launch Configuration has been deprecated. All new accounts created after December 31, 2023 will no longer be able to create Launch Configurations. With the @aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig feature flag set to true, AutoScalingGroup properties used to create a Launch Configuration will now be used to create a LaunchTemplate using a Launch Configuration to LaunchTemplate mapping. Specifically, the following AutoScalingGroup properties will be used to generate a LaunchTemplate:
After the Launch Configuration is replaced with a LaunchTemplate, any new instances launched by the AutoScalingGroup will use the new LaunchTemplate. Existing instances are not affected. To update an existing instance, you can allow the AutoScalingGroup to gradually replace existing instances with new instances based on the termination_policies for the AutoScalingGroup. Alternatively, you can terminate them yourself and force the AutoScalingGroup to launch new instances to maintain the desired_capacity.
Support for creating an AutoScalingGroup from a LaunchTemplate was added in CDK version 2.21.0. Users on a CDK version earlier than version 2.21.0 that need to create an AutoScalingGroup with an account created after December 31, 2023 must update their CDK version to 2.21.0 or later. Users on CDK versions 2.21.0 up to, but not including 2.86.0, must use a manually created LaunchTemplate to create an AutoScalingGroup for accounts created after December 31, 2023. CDK version 2.86.0 or later will automatically generate a LaunchTemplate using the AutoScalingGroup properties mentioned above.
For additional migration information, please see: Migrating to a LaunchTemplate from a Launch Configuration
NOTE: AutoScalingGroup has a property called allow_all_outbound (allowing the instances to contact the
internet) which is set to true by default. Be sure to set this to false if you don't want
your instances to be able to start arbitrary connections. Alternatively, you can specify an existing security
group to attach to the instances that are launched, rather than have the group create a new one.
vpc = nil # AWSCDK::EC2::VPC
my_security_group = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup", {vpc: vpc})
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
security_group: my_security_group,
})
Alternatively, to enable more advanced features, you can create an AutoScalingGroup from a supplied LaunchTemplate:
vpc = nil # AWSCDK::EC2::VPC
launch_template = nil # AWSCDK::EC2::LaunchTemplate
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
launch_template: launch_template,
})
To launch a mixture of Spot and on-demand instances, and/or with multiple instance types, you can create an AutoScalingGroup from a MixedInstancesPolicy:
vpc = nil # AWSCDK::EC2::VPC
launch_template1 = nil # AWSCDK::EC2::LaunchTemplate
launch_template2 = nil # AWSCDK::EC2::LaunchTemplate
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
mixed_instances_policy: {
instances_distribution: {
on_demand_percentage_above_base_capacity: 50,
},
launch_template: launch_template1,
launch_template_overrides: [
{instance_type: AWSCDK::EC2::InstanceType.new("t3.micro")},
{instance_type: AWSCDK::EC2::InstanceType.new("t3a.micro")},
{instance_type: AWSCDK::EC2::InstanceType.new("t4g.micro"), launch_template: launch_template2},
],
},
})
You can specify instances requirements with the instanceRequirements property:
vpc = nil # AWSCDK::EC2::VPC
launch_template1 = nil # AWSCDK::EC2::LaunchTemplate
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
mixed_instances_policy: {
launch_template: launch_template1,
launch_template_overrides: [
{
instance_requirements: {
v_cpu_count: {min: 4, max: 8},
memory_mi_b: {min: 16384},
cpu_manufacturers: ["intel"],
},
},
],
},
})
AMIs control the OS that gets launched when you start your EC2 instance. The EC2 library contains constructs to select the AMI you want to use.
Depending on the type of AMI, you select it a different way.
The latest version of Amazon Linux and Microsoft Windows images are selectable by instantiating one of these classes:
# Pick a Windows edition to use
windows = AWSCDK::EC2::WindowsImage.new(AWSCDK::EC2::WindowsVersion::WINDOWS_SERVER_2019_ENGLISH_FULL_BASE)
# Pick the right Amazon Linux edition. All arguments shown are optional
# and will default to these values when omitted.
amzn_linux = AWSCDK::EC2::AmazonLinuxImage.new({
generation: AWSCDK::EC2::AmazonLinuxGeneration::AMAZON_LINUX,
edition: AWSCDK::EC2::AmazonLinuxEdition::STANDARD,
virtualization: AWSCDK::EC2::AmazonLinuxVirt::HVM,
storage: AWSCDK::EC2::AmazonLinuxStorage::GENERAL_PURPOSE,
})
# For other custom (Linux) images, instantiate a `GenericLinuxImage` with
# a map giving the AMI to in for each region:
linux = AWSCDK::EC2::GenericLinuxImage.new({
"us-east-1" => "ami-97785bed",
"eu-west-1" => "ami-12345678",
})
NOTE: The Amazon Linux images selected will be cached in your
cdk.json, so that your AutoScalingGroups don't automatically change out from under you when you're making unrelated changes. To update to the latest version of Amazon Linux, remove the cache entry from thecontextsection of yourcdk.json.We will add command-line options to make this step easier in the future.
AutoScalingGroups make it possible to raise and lower the number of instances in the group, in response to (or in advance of) changes in workload.
When you create your AutoScalingGroup, you specify a min_capacity and a
max_capacity. AutoScaling policies that respond to metrics will never go higher
or lower than the indicated capacity (but scheduled scaling actions might, see
below).
There are three ways to scale your capacity:
The general pattern of autoscaling will look like this:
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
min_capacity: 5,
max_capacity: 100,
})
This type of scaling scales in and out in deterministics steps that you configure, in response to metric values. For example, your scaling strategy to scale in response to a metric that represents your average worker pool usage might look like this:
Scaling -1 (no change) +1 +3
│ │ │ │ │
├────────┼───────────────────────┼────────┼────────┤
│ │ │ │ │
Worker use 0% 10% 50% 70% 100%
(Note that this is not necessarily a recommended scaling strategy, but it's a possible one. You will have to determine what thresholds are right for you).
Note that in order to set up this scaling strategy, you will have to emit a metric representing your worker utilization from your instances. After that, you would configure the scaling something like this:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
worker_utilization_metric = AWSCDK::CloudWatch::Metric.new({
namespace: "MyService",
metric_name: "WorkerUtilization",
})
auto_scaling_group.scale_on_metric("ScaleToCPU", {
metric: worker_utilization_metric,
scaling_steps: [
{upper: 10, change: -1},
{lower: 50, change: +1},
{lower: 70, change: +3},
],
evaluation_periods: 10,
datapoints_to_alarm: 5,
# Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
# 'change' numbers before as percentages instead of capacity counts.
adjustment_type: AWSCDK::Autoscaling::AdjustmentType::CHANGE_IN_CAPACITY,
})
The AutoScaling construct library will create the required CloudWatch alarms and AutoScaling policies for you.
This type of scaling scales in and out in order to keep a metric around a value you prefer. There are four types of predefined metrics you can track, or you can choose to track a custom metric. If you do choose to track a custom metric, be aware that the metric has to represent instance utilization in some way (AutoScaling will scale out if the metric is higher than the target, and scale in if the metric is lower than the target).
If you configure multiple target tracking policies, AutoScaling will use the one that yields the highest capacity.
The following example scales to keep the CPU usage of your instances around 50% utilization:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.scale_on_cpu_utilization("KeepSpareCPU", {
target_utilization_percent: 50,
})
To scale on average network traffic in and out of your instances:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.scale_on_incoming_bytes("LimitIngressPerInstance", {
target_bytes_per_second: 10 * 1024 * 1024,
})
auto_scaling_group.scale_on_outgoing_bytes("LimitEgressPerInstance", {
target_bytes_per_second: 10 * 1024 * 1024,
})
To scale on the average request count per instance (only works for AutoScalingGroups that have been attached to Application Load Balancers):
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.scale_on_request_count("LimitRPS", {
target_requests_per_second: 1000,
})
This type of scaling is used to change capacities based on time. It works by
changing min_capacity, max_capacity and desired_capacity of the
AutoScalingGroup, and so can be used for two purposes:
min_capacity high or
the max_capacity low.min_capacity and
max_capacity but changing their range over time).A schedule is expressed as a cron expression. The Schedule class has a cron method to help build cron expressions.
The following example scales the fleet out in the morning, going back to natural scaling (all the way down to 1 instance if necessary) at night:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.scale_on_schedule("PrescaleInTheMorning", {
schedule: AWSCDK::Autoscaling::Schedule.cron({hour: "8", minute: "0"}),
min_capacity: 20,
})
auto_scaling_group.scale_on_schedule("AllowDownscalingAtNight", {
schedule: AWSCDK::Autoscaling::Schedule.cron({hour: "20", minute: "0"}),
min_capacity: 1,
})
You can configure the health checks for the instances in the Auto Scaling group.
Possible health check types are EC2, EBS, ELB, and VPC_LATTICE. EC2 is the default health check and cannot be disabled.
If you want to configure the EC2 health check, use the HealthChecks.ec2 method:
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
health_checks: AWSCDK::Autoscaling::HealthChecks.ec2({
grace_period: AWSCDK::Duration.seconds(100),
}),
})
If you also want to configure the additional health checks other than EC2, use the HealthChecks.withAdditionalChecks method.
EC2 is implicitly included, so you can specify types other than EC2.
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
health_checks: AWSCDK::Autoscaling::HealthChecks.with_additional_checks({
grace_period: AWSCDK::Duration.seconds(100),
additional_types: [
AWSCDK::Autoscaling::AdditionalHealthCheckType::EBS,
AWSCDK::Autoscaling::AdditionalHealthCheckType::ELB,
AWSCDK::Autoscaling::AdditionalHealthCheckType::VPC_LATTICE,
],
}),
})
Visit Health checks for instances in an Auto Scaling group for more details.
You can configure an instance maintenance policy for your Auto Scaling group to meet specific capacity requirements during events that cause instances to be replaced, such as an instance refresh or the health check process.
For example, suppose you have an Auto Scaling group that has a small number of instances. You want to avoid the potential disruptions from terminating and then replacing an instance when health checks indicate an impaired instance. With an instance maintenance policy, you can make sure that Amazon EC2 Auto Scaling first launches a new instance and then waits for it to be fully ready before terminating the unhealthy instance.
An instance maintenance policy also helps you minimize any potential disruptions in cases where
multiple instances are replaced at the same time. You set the min_healthy_percentage
and the max_healthy_percentage for the policy, and your Auto Scaling group can only
increase and decrease capacity within that minimum-maximum range when replacing instances.
A larger range increases the number of instances that can be replaced at the same time.
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
max_healthy_percentage: 200,
min_healthy_percentage: 100,
})
Visit Instance maintenance policies for more details.
This type specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
You can only specify the throughput on GP3 volumes.
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
block_devices: [
{
device_name: "gp3-volume",
volume: AWSCDK::Autoscaling::BlockDeviceVolume.ebs(15, {
volume_type: AWSCDK::Autoscaling::EbsDeviceVolumeType::GP3,
throughput: 125,
}),
},
],
})
It is possible to use the CloudFormation Init mechanism to configure the
instances in the AutoScalingGroup. You can write files to it, run commands,
start services, etc. See the documentation of
AWS::CloudFormation::Init
and the documentation of CDK's aws-ec2 library for more information.
When you specify a CloudFormation Init configuration for an AutoScalingGroup:
signals to configure how long CloudFormation
should wait for the instances to successfully configure themselves.update_policy to configure how instances
should be updated when the AutoScalingGroup is updated (for example,
when the AMI is updated). If you don't specify an update policy, a rolling
update is chosen by default.Here's an example of using CloudFormation Init to write a file to the instance hosts on startup:
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
init: AWSCDK::EC2::CloudFormationInit.from_elements(AWSCDK::EC2::InitFile.from_string("/etc/my_instance", "This got written during instance startup")),
signals: AWSCDK::Autoscaling::Signals.wait_for_all({
timeout: AWSCDK::Duration.minutes(10),
}),
})
In normal operation, CloudFormation will send a Create or Update command to an AutoScalingGroup and proceed with the rest of the deployment without waiting for the instances in the AutoScalingGroup.
Configure signals to tell CloudFormation to wait for a specific number of
instances in the AutoScalingGroup to have been started (or failed to start)
before moving on. An instance is supposed to execute the
cfn-signal
program as part of its startup to indicate whether it was started
successfully or not.
If you use CloudFormation Init support (described in the previous section),
the appropriate call to cfn-signal is automatically added to the
AutoScalingGroup's UserData. If you don't use the signals directly, you are
responsible for adding such a call yourself.
The following type of Signals are available:
Signals.waitForAll([options]): wait for all of desired_capacity amount of instances
to have started (recommended).Signals.waitForMinCapacity([options]): wait for a min_capacity amount of instances
to have started (use this if waiting for all instances takes too long and you are happy
with a minimum count of healthy hosts).Signals.waitForCount(count, [options]): wait for a specific amount of instances to have
started.There are two options you can configure:
timeout: maximum time a host startup is allowed to take. If a host does not report
success within this time, it is considered a failure. Default is 5 minutes.min_success_percentage: percentage of hosts that needs to be healthy in order for the
update to succeed. If you set this value lower than 100, some percentage of hosts may
report failure, while still considering the deployment a success. Default is 100%.The update policy describes what should happen to running instances when the definition of the AutoScalingGroup is changed. For example, if you add a command to the UserData of an AutoScalingGroup, do the existing instances get replaced with new instances that have executed the new UserData? Or do the "old" instances just keep on running?
It is recommended to always use an update policy, otherwise the current state of your instances also depends the previous state of your instances, rather than just on your source code. This degrades the reproducibility of your deployments.
The following update policies are available:
UpdatePolicy.none(): leave existing instances alone (not recommended).UpdatePolicy.rollingUpdate([options]): progressively replace the existing
instances with new instances, in small batches. At any point in time,
roughly the same amount of total instances will be running. If the deployment
needs to be rolled back, the fresh instances will be replaced with the "old"
configuration again.UpdatePolicy.replacingUpdate([options]): build a completely fresh copy
of the new AutoScalingGroup next to the old one. Once the AutoScalingGroup
has been successfully created (and the instances started, if signals is
configured on the AutoScalingGroup), the old AutoScalingGroup is deleted.
If the deployment needs to be rolled back, the new AutoScalingGroup is
deleted and the old one is left unchanged.See the documentation of the aws-cdk-lib/aws-ec2 package for more information
about allowing connections between resources backed by instances.
To enable the max instance lifetime support, specify max_instance_lifetime property
for the AutoscalingGroup resource. The value must be between 1 and 365 days(inclusive).
To clear a previously set value, leave this property undefined.
To disable detailed instance monitoring, specify instance_monitoring property
for the AutoscalingGroup resource as Monitoring.BASIC. Otherwise detailed monitoring
will be enabled.
Group metrics are used to monitor group level properties; they describe the group rather than any of its instances (e.g GroupMaxSize, the group maximum size). To enable group metrics monitoring, use the group_metrics property.
All group metrics are reported in a granularity of 1 minute at no additional charge.
See EC2 docs for a list of all available group metrics.
To enable group metrics monitoring using the group_metrics property:
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
# Enable monitoring of all group metrics
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
group_metrics: [AWSCDK::Autoscaling::GroupMetrics.all],
})
# Enable monitoring for a subset of group metrics
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
group_metrics: [AWSCDK::Autoscaling::GroupMetrics.new(AWSCDK::Autoscaling::GroupMetric.MIN_SIZE, AWSCDK::Autoscaling::GroupMetric.MAX_SIZE)],
})
Auto Scaling uses termination policies
to determine which instances it terminates first during scale-in events. You
can specify one or more termination policies with the termination_policies
property:
Custom termination policy with lambda
can be used to determine which instances to terminate based on custom logic.
The custom termination policy can be specified using TerminationPolicy.CUSTOM_LAMBDA_FUNCTION. If this is
specified, you must also supply a value of lambda arn in the termination_policy_custom_lambda_function_arn property and
attach necessary permission
to invoke the lambda function.
If there are multiple termination policies specified,
custom termination policy with lambda TerminationPolicy.CUSTOM_LAMBDA_FUNCTION
must be specified first.
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
arn = nil
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
termination_policies: [
AWSCDK::Autoscaling::TerminationPolicy::CUSTOM_LAMBDA_FUNCTION,
AWSCDK::Autoscaling::TerminationPolicy::OLDEST_INSTANCE,
AWSCDK::Autoscaling::TerminationPolicy::DEFAULT,
],
# terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
termination_policy_custom_lambda_function_arn: arn,
})
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. EC2 Capacity Providers for Amazon ECS requires this attribute be
set to true.
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
new_instances_protected_from_scale_in: true,
})
Indicates whether Capacity Rebalancing is enabled. Otherwise, Capacity Rebalancing is disabled. 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. For more information, see Use Capacity Rebalancing to handle Amazon EC2 Spot Interruptions in the in the Amazon EC2 Auto Scaling User Guide.
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
capacity_rebalance: true,
})
SSM Session Manager makes it possible to connect to your instances from the AWS Console, without preparing SSH keys.
To do so, you need to:
ssmSessionPermissions: true.If these conditions are met, you can connect to the instance from the EC2 Console. Example:
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::T3, AWSCDK::EC2::InstanceSize::MICRO),
# Amazon Linux 2 comes with SSM Agent by default
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
# Turn on SSM
ssm_session_permissions: true,
})
You can configure EC2 Instance Metadata Service options to either allow both IMDSv1 and IMDSv2 or enforce IMDSv2 when interacting with the IMDS.
To do this for a single AutoScalingGroup, you can use set the require_imdsv2 property.
The example below demonstrates IMDSv2 being required on a single AutoScalingGroup:
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
require_imdsv2: true,
})
You can also use AutoScalingGroupRequireImdsv2Aspect to apply the operation to multiple AutoScalingGroups.
The example below demonstrates the AutoScalingGroupRequireImdsv2Aspect being used to require IMDSv2 for all AutoScalingGroups in a stack:
aspect = AWSCDK::Autoscaling::AutoScalingGroupRequireImdsv2Aspect.new
AWSCDK::Aspects.of(self).add(aspect)
Auto Scaling offers a warm pool which gives an ability to decrease latency for applications that have exceptionally long boot times. You can create a warm pool with default parameters as below:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.add_warm_pool
You can also customize a warm pool by configuring parameters:
auto_scaling_group = nil # AWSCDK::Autoscaling::AutoScalingGroup
auto_scaling_group.add_warm_pool({
min_size: 1,
reuse_on_scale_in: true,
})
You can use the default instance warmup feature to improve the Amazon CloudWatch metrics used for dynamic scaling. When default instance warmup is not enabled, each instance starts contributing usage data to the aggregated metrics as soon as the instance reaches the InService state. However, if you enable default instance warmup, this lets your instances finish warming up before they contribute the usage data.
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.
To set up Default Instance Warming for an autoscaling group, simply pass it in as a prop
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
default_instance_warmup: AWSCDK::Duration.seconds(5),
})
You can use a keyPair to build your asg when you decide not to use a ready-made LanchTemplate.
To configure KeyPair for an autoscaling group, pass the key_pair as a prop:
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
my_key_pair = AWSCDK::EC2::KeyPair.new(self, "MyKeyPair")
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
key_pair: my_key_pair,
})
If launches fail in an Availability Zone, the following strategies are available.
BALANCED_BEST_EFFORT (default) - If launches fail in an Availability Zone, Auto Scaling will attempt to launch in another healthy Availability Zone instead.BALANCED_ONLY - If launches fail in an Availability Zone, Auto Scaling will continue to attempt to launch in the unhealthy zone to preserve a balanced distribution.vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# ...
az_capacity_distribution_strategy: AWSCDK::Autoscaling::CapacityDistributionStrategy::BALANCED_ONLY,
})
You can enable deletion protection to prevent your Auto Scaling group from being accidentally deleted. Deletion protection blocks the DeleteAutoScalingGroup API operation, requiring you to first update the deletion protection setting before you can delete the Auto Scaling group.
vpc = nil # AWSCDK::EC2::VPC
AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::T3, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::EC2::MachineImage.latest_amazon_linux2,
deletion_protection: AWSCDK::Autoscaling::DeletionProtection::PREVENT_ALL_DELETION,
})
The following deletion protection levels are available:
DeletionProtection.NONE (default) - No deletion protection. The Auto Scaling group can be deleted with or without the force delete option.DeletionProtection.PREVENT_FORCE_DELETION - Prevents force deletion operations. This allows deletion of empty Auto Scaling groups but blocks force deletion that would terminate all instances.DeletionProtection.PREVENT_ALL_DELETION - Prevents all deletion operations. This provides the strongest protection and requires explicitly disabling deletion protection before the Auto Scaling group can be deleted.Note: When using PREVENT_ALL_DELETION, you must first update the deletion protection setting before deleting the CloudFormation stack containing the Auto Scaling group.
You can configure an instance lifecycle policy to control how instances are handled during lifecycle events, particularly when lifecycle hooks are abandoned or fail. This allows fine-grained control over when to preserve instances for manual intervention.
The instance lifecycle policy defines retention triggers that specify when instances should be moved to a Retained state rather than terminated. Retained instances don't count toward desired capacity and remain until you manually terminate them.
Important: To use instance lifecycle policies in your Auto Scaling group, you must also configure a termination lifecycle hook. If you configure an instance lifecycle policy but don't have any termination lifecycle hooks, the policy has no effect. Instance lifecycle policies will only apply when termination lifecycle actions are abandoned, not when they complete successfully with the CONTINUE result.
vpc = nil # AWSCDK::EC2::VPC
instance_type = nil # AWSCDK::EC2::InstanceType
machine_image = nil # AWSCDK::EC2::IMachineImage
asg = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
vpc: vpc,
instance_type: instance_type,
machine_image: machine_image,
# Configure instance lifecycle policy
instance_lifecycle_policy: {
retention_triggers: {
terminate_hook_abandon: AWSCDK::Autoscaling::TerminateHookAbandonAction::RETAIN,
},
},
})
# Add termination lifecycle hook (required for the policy to take effect)
asg.add_lifecycle_hook("TerminationHook", {
lifecycle_transition: AWSCDK::Autoscaling::LifecycleTransition::INSTANCE_TERMINATING,
})
The terminate_hook_abandon trigger specifies the action when a termination lifecycle hook is abandoned due to failure, timeout, or explicit abandonment. You can set it to:
RETAIN - Move instances to a Retained state for manual investigationTERMINATE - Use default termination behavior (instances are terminated normally)This feature is particularly useful for debugging failed instances or preserving instances that contain important data during lifecycle hook failures.