Amazon EC2 Auto Scaling Construct Library
This module is part of the AWS Cloud Development Kit project.
Auto Scaling Group
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:
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
// The latest Amazon Linux 2 image
machineImage: ec2.MachineImage.latestAmazonLinux2(),
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
# The latest Amazon Linux 2 image
machine_image=ec2.MachineImage.latest_amazon_linux2()
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
// The latest Amazon Linux 2 image
.machineImage(MachineImage.latestAmazonLinux2())
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
// The latest Amazon Linux 2 image
MachineImage = MachineImage.LatestAmazonLinux2()
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
// The latest Amazon Linux 2 image
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
})
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:
- machineImage
- keyName (deprecated, prefer keyPair)
- keyPair
- instanceType
- instanceMonitoring
- securityGroup
- role
- userData
- associatePublicIpAddress
- spotPrice
- blockDevices
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 terminationPolicies for the AutoScalingGroup. Alternatively, you can terminate them yourself and force the AutoScalingGroup to launch new instances to maintain the desiredCapacity.
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 allowAllOutbound (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.
declare const vpc: ec2.Vpc;
const mySecurityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
securityGroup: mySecurityGroup,
});
# vpc: ec2.Vpc
my_security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2(),
security_group=my_security_group
)
Vpc vpc;
SecurityGroup mySecurityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2())
.securityGroup(mySecurityGroup)
.build();
Vpc vpc;
var mySecurityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2(),
SecurityGroup = mySecurityGroup
});
var vpc Vpc
mySecurityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
Vpc: Vpc,
})
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
SecurityGroup: mySecurityGroup,
})
Alternatively, to enable more advanced features, you can create an AutoScalingGroup from a supplied LaunchTemplate:
declare const vpc: ec2.Vpc;
declare const launchTemplate: ec2.LaunchTemplate;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
launchTemplate: launchTemplate
});
# vpc: ec2.Vpc
# launch_template: ec2.LaunchTemplate
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
launch_template=launch_template
)
Vpc vpc;
LaunchTemplate launchTemplate;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.launchTemplate(launchTemplate)
.build();
Vpc vpc;
LaunchTemplate launchTemplate;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
LaunchTemplate = launchTemplate
});
var vpc Vpc
var launchTemplate LaunchTemplate
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
LaunchTemplate: launchTemplate,
})
To launch a mixture of Spot and on-demand instances, and/or with multiple instance types, you can create an AutoScalingGroup from a MixedInstancesPolicy:
declare const vpc: ec2.Vpc;
declare const launchTemplate1: ec2.LaunchTemplate;
declare const launchTemplate2: ec2.LaunchTemplate;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
mixedInstancesPolicy: {
instancesDistribution: {
onDemandPercentageAboveBaseCapacity: 50, // Mix Spot and On-Demand instances
},
launchTemplate: launchTemplate1,
launchTemplateOverrides: [ // Mix multiple instance types
{ instanceType: new ec2.InstanceType('t3.micro') },
{ instanceType: new ec2.InstanceType('t3a.micro') },
{ instanceType: new ec2.InstanceType('t4g.micro'), launchTemplate: launchTemplate2 },
],
}
});
# vpc: ec2.Vpc
# launch_template1: ec2.LaunchTemplate
# launch_template2: ec2.LaunchTemplate
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
mixed_instances_policy=autoscaling.MixedInstancesPolicy(
instances_distribution=autoscaling.InstancesDistribution(
on_demand_percentage_above_base_capacity=50
),
launch_template=launch_template1,
launch_template_overrides=[autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t3.micro")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t3a.micro")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t4g.micro"), launch_template=launch_template2)]
)
)
Vpc vpc;
LaunchTemplate launchTemplate1;
LaunchTemplate launchTemplate2;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.mixedInstancesPolicy(MixedInstancesPolicy.builder()
.instancesDistribution(InstancesDistribution.builder()
.onDemandPercentageAboveBaseCapacity(50)
.build())
.launchTemplate(launchTemplate1)
.launchTemplateOverrides(List.of(LaunchTemplateOverrides.builder().instanceType(new InstanceType("t3.micro")).build(), LaunchTemplateOverrides.builder().instanceType(new InstanceType("t3a.micro")).build(), LaunchTemplateOverrides.builder().instanceType(new InstanceType("t4g.micro")).launchTemplate(launchTemplate2).build()))
.build())
.build();
Vpc vpc;
LaunchTemplate launchTemplate1;
LaunchTemplate launchTemplate2;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
MixedInstancesPolicy = new MixedInstancesPolicy {
InstancesDistribution = new InstancesDistribution {
OnDemandPercentageAboveBaseCapacity = 50
},
LaunchTemplate = launchTemplate1,
LaunchTemplateOverrides = new [] { new LaunchTemplateOverrides { InstanceType = new InstanceType("t3.micro") }, new LaunchTemplateOverrides { InstanceType = new InstanceType("t3a.micro") }, new LaunchTemplateOverrides { InstanceType = new InstanceType("t4g.micro"), LaunchTemplate = launchTemplate2 } }
}
});
var vpc Vpc
var launchTemplate1 LaunchTemplate
var launchTemplate2 LaunchTemplate
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
MixedInstancesPolicy: &MixedInstancesPolicy{
InstancesDistribution: &InstancesDistribution{
OnDemandPercentageAboveBaseCapacity: jsii.Number(50),
},
LaunchTemplate: launchTemplate1,
LaunchTemplateOverrides: []LaunchTemplateOverrides{
&LaunchTemplateOverrides{
InstanceType: ec2.NewInstanceType(jsii.String("t3.micro")),
},
&LaunchTemplateOverrides{
InstanceType: ec2.NewInstanceType(jsii.String("t3a.micro")),
},
&LaunchTemplateOverrides{
InstanceType: ec2.NewInstanceType(jsii.String("t4g.micro")),
LaunchTemplate: launchTemplate2,
},
},
},
})
You can specify instances requirements with the instanceRequirements property:
declare const vpc: ec2.Vpc;
declare const launchTemplate1: ec2.LaunchTemplate;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
mixedInstancesPolicy: {
launchTemplate: launchTemplate1,
launchTemplateOverrides: [
{
instanceRequirements: {
vCpuCount: { min: 4, max: 8 },
memoryMiB: { min: 16384 },
cpuManufacturers: ['intel'],
},
}
],
}
});
# vpc: ec2.Vpc
# launch_template1: ec2.LaunchTemplate
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
mixed_instances_policy=autoscaling.MixedInstancesPolicy(
launch_template=launch_template1,
launch_template_overrides=[autoscaling.LaunchTemplateOverrides(
instance_requirements=autoscaling.CfnAutoScalingGroup.InstanceRequirementsProperty(
v_cpu_count=autoscaling.CfnAutoScalingGroup.VCpuCountRequestProperty(min=4, max=8),
memory_mi_b=autoscaling.CfnAutoScalingGroup.MemoryMiBRequestProperty(min=16384),
cpu_manufacturers=["intel"]
)
)
]
)
)
Vpc vpc;
LaunchTemplate launchTemplate1;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.mixedInstancesPolicy(MixedInstancesPolicy.builder()
.launchTemplate(launchTemplate1)
.launchTemplateOverrides(List.of(LaunchTemplateOverrides.builder()
.instanceRequirements(InstanceRequirementsProperty.builder()
.vCpuCount(VCpuCountRequestProperty.builder().min(4).max(8).build())
.memoryMiB(MemoryMiBRequestProperty.builder().min(16384).build())
.cpuManufacturers(List.of("intel"))
.build())
.build()))
.build())
.build();
Vpc vpc;
LaunchTemplate launchTemplate1;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
MixedInstancesPolicy = new MixedInstancesPolicy {
LaunchTemplate = launchTemplate1,
LaunchTemplateOverrides = new [] { new LaunchTemplateOverrides {
InstanceRequirements = new InstanceRequirementsProperty {
VCpuCount = new VCpuCountRequestProperty { Min = 4, Max = 8 },
MemoryMiB = new MemoryMiBRequestProperty { Min = 16384 },
CpuManufacturers = new [] { "intel" }
}
} }
}
});
var vpc Vpc
var launchTemplate1 LaunchTemplate
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
MixedInstancesPolicy: &MixedInstancesPolicy{
LaunchTemplate: launchTemplate1,
LaunchTemplateOverrides: []LaunchTemplateOverrides{
&LaunchTemplateOverrides{
InstanceRequirements: &InstanceRequirementsProperty{
VCpuCount: &VCpuCountRequestProperty{
Min: jsii.Number(4),
Max: jsii.Number(8),
},
MemoryMiB: &MemoryMiBRequestProperty{
Min: jsii.Number(16384),
},
CpuManufacturers: []*string{
jsii.String("intel"),
},
},
},
},
},
})
Machine Images (AMIs)
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
const windows = new ec2.WindowsImage(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.
const amznLinux = new ec2.AmazonLinuxImage({
generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX,
edition: ec2.AmazonLinuxEdition.STANDARD,
virtualization: ec2.AmazonLinuxVirt.HVM,
storage: ec2.AmazonLinuxStorage.GENERAL_PURPOSE,
});
// For other custom (Linux) images, instantiate a `GenericLinuxImage` with
// a map giving the AMI to in for each region:
const linux = new ec2.GenericLinuxImage({
'us-east-1': 'ami-97785bed',
'eu-west-1': 'ami-12345678',
// ...
});
# Pick a Windows edition to use
windows = ec2.WindowsImage(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 = ec2.AmazonLinuxImage(
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
edition=ec2.AmazonLinuxEdition.STANDARD,
virtualization=ec2.AmazonLinuxVirt.HVM,
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)
# For other custom (Linux) images, instantiate a `GenericLinuxImage` with
# a map giving the AMI to in for each region:
linux = ec2.GenericLinuxImage({
"us-east-1": "ami-97785bed",
"eu-west-1": "ami-12345678"
})
// Pick a Windows edition to use
WindowsImage windows = new WindowsImage(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.
AmazonLinuxImage amznLinux = AmazonLinuxImage.Builder.create()
.generation(AmazonLinuxGeneration.AMAZON_LINUX)
.edition(AmazonLinuxEdition.STANDARD)
.virtualization(AmazonLinuxVirt.HVM)
.storage(AmazonLinuxStorage.GENERAL_PURPOSE)
.build();
// For other custom (Linux) images, instantiate a `GenericLinuxImage` with
// a map giving the AMI to in for each region:
GenericLinuxImage linux = new GenericLinuxImage(Map.of(
"us-east-1", "ami-97785bed",
"eu-west-1", "ami-12345678"));
// Pick a Windows edition to use
var windows = new WindowsImage(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.
var amznLinux = new AmazonLinuxImage(new AmazonLinuxImageProps {
Generation = AmazonLinuxGeneration.AMAZON_LINUX,
Edition = AmazonLinuxEdition.STANDARD,
Virtualization = AmazonLinuxVirt.HVM,
Storage = AmazonLinuxStorage.GENERAL_PURPOSE
});
// For other custom (Linux) images, instantiate a `GenericLinuxImage` with
// a map giving the AMI to in for each region:
var linux = new GenericLinuxImage(new Dictionary<string, string> {
{ "us-east-1", "ami-97785bed" },
{ "eu-west-1", "ami-12345678" }
});
// Pick a Windows edition to use
windows := ec2.NewWindowsImage(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.
amznLinux := ec2.NewAmazonLinuxImage(&AmazonLinuxImageProps{
Generation: ec2.AmazonLinuxGeneration_AMAZON_LINUX,
Edition: ec2.AmazonLinuxEdition_STANDARD,
Virtualization: ec2.AmazonLinuxVirt_HVM,
Storage: ec2.AmazonLinuxStorage_GENERAL_PURPOSE,
})
// For other custom (Linux) images, instantiate a `GenericLinuxImage` with
// a map giving the AMI to in for each region:
linux := ec2.NewGenericLinuxImage(map[string]*string{
"us-east-1": jsii.String("ami-97785bed"),
"eu-west-1": jsii.String("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.
AutoScaling Instance Counts
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 minCapacity and a maxCapacity. 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:
- In response to a metric (also known as step scaling); for example, you might want to scale out if the CPU usage across your cluster starts to rise, and scale in when it drops again.
- By trying to keep a certain metric around a given value (also known as target tracking scaling); you might want to automatically scale out and in to keep your CPU usage around 50%.
- On a schedule; you might want to organize your scaling around traffic flows you expect, by scaling out in the morning and scaling in in the evening.
The general pattern of autoscaling will look like this:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
minCapacity: 5,
maxCapacity: 100
// ...
});
// Then call one of the scaling methods (explained below)
//
// autoScalingGroup.scaleOnMetric(...);
//
// autoScalingGroup.scaleOnCpuUtilization(...);
// autoScalingGroup.scaleOnIncomingBytes(...);
// autoScalingGroup.scaleOnOutgoingBytes(...);
// autoScalingGroup.scaleOnRequestCount(...);
// autoScalingGroup.scaleToTrackMetric(...);
//
// autoScalingGroup.scaleOnSchedule(...);
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
min_capacity=5,
max_capacity=100
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
.minCapacity(5)
.maxCapacity(100)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
MinCapacity = 5,
MaxCapacity = 100
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
MinCapacity: jsii.Number(5),
MaxCapacity: jsii.Number(100),
})
Step Scaling
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:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
const workerUtilizationMetric = new cloudwatch.Metric({
namespace: 'MyService',
metricName: 'WorkerUtilization'
});
autoScalingGroup.scaleOnMetric('ScaleToCPU', {
metric: workerUtilizationMetric,
scalingSteps: [
{ upper: 10, change: -1 },
{ lower: 50, change: +1 },
{ lower: 70, change: +3 },
],
evaluationPeriods: 10,
datapointsToAlarm: 5,
// Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
// 'change' numbers before as percentages instead of capacity counts.
adjustmentType: autoscaling.AdjustmentType.CHANGE_IN_CAPACITY,
});
# auto_scaling_group: autoscaling.AutoScalingGroup
worker_utilization_metric = cloudwatch.Metric(
namespace="MyService",
metric_name="WorkerUtilization"
)
auto_scaling_group.scale_on_metric("ScaleToCPU",
metric=worker_utilization_metric,
scaling_steps=[autoscaling.ScalingInterval(upper=10, change=-1), autoscaling.ScalingInterval(lower=50, change=+1), autoscaling.ScalingInterval(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=autoscaling.AdjustmentType.CHANGE_IN_CAPACITY
)
AutoScalingGroup autoScalingGroup;
Metric workerUtilizationMetric = Metric.Builder.create()
.namespace("MyService")
.metricName("WorkerUtilization")
.build();
autoScalingGroup.scaleOnMetric("ScaleToCPU", BasicStepScalingPolicyProps.builder()
.metric(workerUtilizationMetric)
.scalingSteps(List.of(ScalingInterval.builder().upper(10).change(-1).build(), ScalingInterval.builder().lower(50).change(+1).build(), ScalingInterval.builder().lower(70).change(+3).build()))
.evaluationPeriods(10)
.datapointsToAlarm(5)
// Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
// 'change' numbers before as percentages instead of capacity counts.
.adjustmentType(AdjustmentType.CHANGE_IN_CAPACITY)
.build());
AutoScalingGroup autoScalingGroup;
var workerUtilizationMetric = new Metric(new MetricProps {
Namespace = "MyService",
MetricName = "WorkerUtilization"
});
autoScalingGroup.ScaleOnMetric("ScaleToCPU", new BasicStepScalingPolicyProps {
Metric = workerUtilizationMetric,
ScalingSteps = new [] { new ScalingInterval { Upper = 10, Change = -1 }, new ScalingInterval { Lower = 50, Change = +1 }, new ScalingInterval { Lower = 70, Change = +3 } },
EvaluationPeriods = 10,
DatapointsToAlarm = 5,
// Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
// 'change' numbers before as percentages instead of capacity counts.
AdjustmentType = AdjustmentType.CHANGE_IN_CAPACITY
});
var autoScalingGroup AutoScalingGroup
workerUtilizationMetric := cloudwatch.NewMetric(&MetricProps{
Namespace: jsii.String("MyService"),
MetricName: jsii.String("WorkerUtilization"),
})
autoScalingGroup.scaleOnMetric(jsii.String("ScaleToCPU"), &BasicStepScalingPolicyProps{
Metric: workerUtilizationMetric,
ScalingSteps: []ScalingInterval{
&ScalingInterval{
Upper: jsii.Number(10),
Change: -jsii.Number(1),
},
&ScalingInterval{
Lower: jsii.Number(50),
Change: +jsii.Number(1),
},
&ScalingInterval{
Lower: jsii.Number(70),
Change: +jsii.Number(3),
},
},
EvaluationPeriods: jsii.Number(10),
DatapointsToAlarm: jsii.Number(5),
// Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
// 'change' numbers before as percentages instead of capacity counts.
AdjustmentType: autoscaling.AdjustmentType_CHANGE_IN_CAPACITY,
})
The AutoScaling construct library will create the required CloudWatch alarms and AutoScaling policies for you.
Target Tracking Scaling
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:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.scaleOnCpuUtilization('KeepSpareCPU', {
targetUtilizationPercent: 50
});
# auto_scaling_group: autoscaling.AutoScalingGroup
auto_scaling_group.scale_on_cpu_utilization("KeepSpareCPU",
target_utilization_percent=50
)
AutoScalingGroup autoScalingGroup;
autoScalingGroup.scaleOnCpuUtilization("KeepSpareCPU", CpuUtilizationScalingProps.builder()
.targetUtilizationPercent(50)
.build());
AutoScalingGroup autoScalingGroup;
autoScalingGroup.ScaleOnCpuUtilization("KeepSpareCPU", new CpuUtilizationScalingProps {
TargetUtilizationPercent = 50
});
var autoScalingGroup AutoScalingGroup
autoScalingGroup.scaleOnCpuUtilization(jsii.String("KeepSpareCPU"), &CpuUtilizationScalingProps{
TargetUtilizationPercent: jsii.Number(50),
})
To scale on average network traffic in and out of your instances:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.scaleOnIncomingBytes('LimitIngressPerInstance', {
targetBytesPerSecond: 10 * 1024 * 1024 // 10 MB/s
});
autoScalingGroup.scaleOnOutgoingBytes('LimitEgressPerInstance', {
targetBytesPerSecond: 10 * 1024 * 1024 // 10 MB/s
});
# auto_scaling_group: 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
)
AutoScalingGroup autoScalingGroup;
autoScalingGroup.scaleOnIncomingBytes("LimitIngressPerInstance", NetworkUtilizationScalingProps.builder()
.targetBytesPerSecond(10 * 1024 * 1024)
.build());
autoScalingGroup.scaleOnOutgoingBytes("LimitEgressPerInstance", NetworkUtilizationScalingProps.builder()
.targetBytesPerSecond(10 * 1024 * 1024)
.build());
AutoScalingGroup autoScalingGroup;
autoScalingGroup.ScaleOnIncomingBytes("LimitIngressPerInstance", new NetworkUtilizationScalingProps {
TargetBytesPerSecond = 10 * 1024 * 1024
});
autoScalingGroup.ScaleOnOutgoingBytes("LimitEgressPerInstance", new NetworkUtilizationScalingProps {
TargetBytesPerSecond = 10 * 1024 * 1024
});
var autoScalingGroup AutoScalingGroup
autoScalingGroup.scaleOnIncomingBytes(jsii.String("LimitIngressPerInstance"), &NetworkUtilizationScalingProps{
TargetBytesPerSecond: jsii.Number(10 * 1024 * 1024),
})
autoScalingGroup.scaleOnOutgoingBytes(jsii.String("LimitEgressPerInstance"), &NetworkUtilizationScalingProps{
TargetBytesPerSecond: jsii.Number(10 * 1024 * 1024),
})
To scale on the average request count per instance (only works for AutoScalingGroups that have been attached to Application Load Balancers):
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.scaleOnRequestCount('LimitRPS', {
targetRequestsPerSecond: 1000
});
# auto_scaling_group: autoscaling.AutoScalingGroup
auto_scaling_group.scale_on_request_count("LimitRPS",
target_requests_per_second=1000
)
AutoScalingGroup autoScalingGroup;
autoScalingGroup.scaleOnRequestCount("LimitRPS", RequestCountScalingProps.builder()
.targetRequestsPerSecond(1000)
.build());
AutoScalingGroup autoScalingGroup;
autoScalingGroup.ScaleOnRequestCount("LimitRPS", new RequestCountScalingProps {
TargetRequestsPerSecond = 1000
});
var autoScalingGroup AutoScalingGroup
autoScalingGroup.scaleOnRequestCount(jsii.String("LimitRPS"), &RequestCountScalingProps{
TargetRequestsPerSecond: jsii.Number(1000),
})
Scheduled Scaling
This type of scaling is used to change capacities based on time. It works by changing minCapacity, maxCapacity and desiredCapacity of the AutoScalingGroup, and so can be used for two purposes:
- Scale in and out on a schedule by setting the
minCapacityhigh or themaxCapacitylow. - Still allow the regular scaling actions to do their job, but restrict the range they can scale over (by setting both
minCapacityandmaxCapacitybut 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:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.scaleOnSchedule('PrescaleInTheMorning', {
schedule: autoscaling.Schedule.cron({ hour: '8', minute: '0' }),
minCapacity: 20,
});
autoScalingGroup.scaleOnSchedule('AllowDownscalingAtNight', {
schedule: autoscaling.Schedule.cron({ hour: '20', minute: '0' }),
minCapacity: 1
});
# auto_scaling_group: autoscaling.AutoScalingGroup
auto_scaling_group.scale_on_schedule("PrescaleInTheMorning",
schedule=autoscaling.Schedule.cron(hour="8", minute="0"),
min_capacity=20
)
auto_scaling_group.scale_on_schedule("AllowDownscalingAtNight",
schedule=autoscaling.Schedule.cron(hour="20", minute="0"),
min_capacity=1
)
AutoScalingGroup autoScalingGroup;
autoScalingGroup.scaleOnSchedule("PrescaleInTheMorning", BasicScheduledActionProps.builder()
.schedule(Schedule.cron(CronOptions.builder().hour("8").minute("0").build()))
.minCapacity(20)
.build());
autoScalingGroup.scaleOnSchedule("AllowDownscalingAtNight", BasicScheduledActionProps.builder()
.schedule(Schedule.cron(CronOptions.builder().hour("20").minute("0").build()))
.minCapacity(1)
.build());
AutoScalingGroup autoScalingGroup;
autoScalingGroup.ScaleOnSchedule("PrescaleInTheMorning", new BasicScheduledActionProps {
Schedule = Schedule.Cron(new CronOptions { Hour = "8", Minute = "0" }),
MinCapacity = 20
});
autoScalingGroup.ScaleOnSchedule("AllowDownscalingAtNight", new BasicScheduledActionProps {
Schedule = Schedule.Cron(new CronOptions { Hour = "20", Minute = "0" }),
MinCapacity = 1
});
var autoScalingGroup AutoScalingGroup
autoScalingGroup.scaleOnSchedule(jsii.String("PrescaleInTheMorning"), &BasicScheduledActionProps{
Schedule: autoscaling.Schedule_Cron(&CronOptions{
Hour: jsii.String("8"),
Minute: jsii.String("0"),
}),
MinCapacity: jsii.Number(20),
})
autoScalingGroup.scaleOnSchedule(jsii.String("AllowDownscalingAtNight"), &BasicScheduledActionProps{
Schedule: autoscaling.Schedule_*Cron(&CronOptions{
Hour: jsii.String("20"),
Minute: jsii.String("0"),
}),
MinCapacity: jsii.Number(1),
})
Health checks for instances
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:
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
healthChecks: autoscaling.HealthChecks.ec2({
gracePeriod: Duration.seconds(100),
}),
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2(),
health_checks=autoscaling.HealthChecks.ec2(
grace_period=Duration.seconds(100)
)
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2())
.healthChecks(HealthChecks.ec2(Ec2HealthChecksOptions.builder()
.gracePeriod(Duration.seconds(100))
.build()))
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2(),
HealthChecks = HealthChecks.Ec2(new Ec2HealthChecksOptions {
GracePeriod = Duration.Seconds(100)
})
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
HealthChecks: autoscaling.HealthChecks_Ec2(&Ec2HealthChecksOptions{
GracePeriod: awscdk.Duration_Seconds(jsii.Number(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.
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
healthChecks: autoscaling.HealthChecks.withAdditionalChecks({
gracePeriod: Duration.seconds(100),
additionalTypes: [
autoscaling.AdditionalHealthCheckType.EBS,
autoscaling.AdditionalHealthCheckType.ELB,
autoscaling.AdditionalHealthCheckType.VPC_LATTICE,
],
}),
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2(),
health_checks=autoscaling.HealthChecks.with_additional_checks(
grace_period=Duration.seconds(100),
additional_types=[autoscaling.AdditionalHealthCheckType.EBS, autoscaling.AdditionalHealthCheckType.ELB, autoscaling.AdditionalHealthCheckType.VPC_LATTICE
]
)
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2())
.healthChecks(HealthChecks.withAdditionalChecks(AdditionalHealthChecksOptions.builder()
.gracePeriod(Duration.seconds(100))
.additionalTypes(List.of(AdditionalHealthCheckType.EBS, AdditionalHealthCheckType.ELB, AdditionalHealthCheckType.VPC_LATTICE))
.build()))
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2(),
HealthChecks = HealthChecks.WithAdditionalChecks(new AdditionalHealthChecksOptions {
GracePeriod = Duration.Seconds(100),
AdditionalTypes = new [] { AdditionalHealthCheckType.EBS, AdditionalHealthCheckType.ELB, AdditionalHealthCheckType.VPC_LATTICE }
})
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
HealthChecks: autoscaling.HealthChecks_WithAdditionalChecks(&AdditionalHealthChecksOptions{
GracePeriod: awscdk.Duration_Seconds(jsii.Number(100)),
AdditionalTypes: []AdditionalHealthCheckType{
autoscaling.AdditionalHealthCheckType_EBS,
autoscaling.AdditionalHealthCheckType_ELB,
autoscaling.AdditionalHealthCheckType_VPC_LATTICE,
},
}),
})
Visit Health checks for instances in an Auto Scaling group for more details.
Instance Maintenance Policy
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 minHealthyPercentage and the maxHealthyPercentage 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.
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
maxHealthyPercentage: 200,
minHealthyPercentage: 100,
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2(),
max_healthy_percentage=200,
min_healthy_percentage=100
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2())
.maxHealthyPercentage(200)
.minHealthyPercentage(100)
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2(),
MaxHealthyPercentage = 200,
MinHealthyPercentage = 100
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE2, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
MaxHealthyPercentage: jsii.Number(200),
MinHealthyPercentage: jsii.Number(100),
})
Visit Instance maintenance policies for more details.
Block Devices
This type specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
GP3 Volumes
You can only specify the throughput on GP3 volumes.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
blockDevices: [
{
deviceName: 'gp3-volume',
volume: autoscaling.BlockDeviceVolume.ebs(15, {
volumeType: autoscaling.EbsDeviceVolumeType.GP3,
throughput: 125,
}),
},
],
// ...
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
block_devices=[autoscaling.BlockDevice(
device_name="gp3-volume",
volume=autoscaling.BlockDeviceVolume.ebs(15,
volume_type=autoscaling.EbsDeviceVolumeType.GP3,
throughput=125
)
)
]
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
.blockDevices(List.of(BlockDevice.builder()
.deviceName("gp3-volume")
.volume(BlockDeviceVolume.ebs(15, EbsDeviceOptions.builder()
.volumeType(EbsDeviceVolumeType.GP3)
.throughput(125)
.build()))
.build()))
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
BlockDevices = new [] { new BlockDevice {
DeviceName = "gp3-volume",
Volume = BlockDeviceVolume.Ebs(15, new EbsDeviceOptions {
VolumeType = EbsDeviceVolumeType.GP3,
Throughput = 125
})
} }
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
BlockDevices: []BlockDevice{
&BlockDevice{
DeviceName: jsii.String("gp3-volume"),
Volume: autoscaling.BlockDeviceVolume_Ebs(jsii.Number(15), &EbsDeviceOptions{
VolumeType: autoscaling.EbsDeviceVolumeType_GP3,
Throughput: jsii.Number(125),
}),
},
},
})
Configuring Instances using CloudFormation Init
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:
- you must also specify
signalsto configure how long CloudFormation should wait for the instances to successfully configure themselves. - you should also specify an
updatePolicyto 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:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
init: ec2.CloudFormationInit.fromElements(
ec2.InitFile.fromString('/etc/my_instance', 'This got written during instance startup'),
),
signals: autoscaling.Signals.waitForAll({
timeout: Duration.minutes(10),
}),
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
init=ec2.CloudFormationInit.from_elements(
ec2.InitFile.from_string("/etc/my_instance", "This got written during instance startup")),
signals=autoscaling.Signals.wait_for_all(
timeout=Duration.minutes(10)
)
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.init(CloudFormationInit.fromElements(InitFile.fromString("/etc/my_instance", "This got written during instance startup")))
.signals(Signals.waitForAll(SignalsOptions.builder()
.timeout(Duration.minutes(10))
.build()))
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
Init = CloudFormationInit.FromElements(InitFile.FromString("/etc/my_instance", "This got written during instance startup")),
Signals = Signals.WaitForAll(new SignalsOptions {
Timeout = Duration.Minutes(10)
})
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
Init: ec2.CloudFormationInit_FromElements(ec2.InitFile_FromString(jsii.String("/etc/my_instance"), jsii.String("This got written during instance startup"))),
Signals: autoscaling.Signals_WaitForAll(&SignalsOptions{
Timeout: awscdk.Duration_Minutes(jsii.Number(10)),
}),
})
Signals
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 ofdesiredCapacityamount of instances to have started (recommended).Signals.waitForMinCapacity([options]): wait for aminCapacityamount 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.minSuccessPercentage: 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%.
Update Policy
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, ifsignalsis 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.UpdatePolicy.instanceRefresh([options]): gradually replace the existing instances with new instances by having Amazon EC2 Auto Scaling perform an instance refresh, keeping a configurable percentage of the group healthy and in service throughout.
To customize the instance refresh, pass options:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
declare const alarm: cloudwatch.Alarm;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
updatePolicy: autoscaling.UpdatePolicy.instanceRefresh({
strategy: autoscaling.InstanceRefreshStrategy.ROLLING,
minHealthyPercentage: 90,
maxHealthyPercentage: 100,
instanceWarmup: Duration.seconds(300),
checkpointPercentages: [50, 100],
checkpointDelay: Duration.minutes(10),
alarms: [alarm],
}),
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
# alarm: cloudwatch.Alarm
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
update_policy=autoscaling.UpdatePolicy.instance_refresh(
strategy=autoscaling.InstanceRefreshStrategy.ROLLING,
min_healthy_percentage=90,
max_healthy_percentage=100,
instance_warmup=Duration.seconds(300),
checkpoint_percentages=[50, 100],
checkpoint_delay=Duration.minutes(10),
alarms=[alarm]
)
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
Alarm alarm;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
.updatePolicy(UpdatePolicy.instanceRefresh(InstanceRefreshOptions.builder()
.strategy(InstanceRefreshStrategy.ROLLING)
.minHealthyPercentage(90)
.maxHealthyPercentage(100)
.instanceWarmup(Duration.seconds(300))
.checkpointPercentages(List.of(50, 100))
.checkpointDelay(Duration.minutes(10))
.alarms(List.of(alarm))
.build()))
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
Alarm alarm;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
UpdatePolicy = UpdatePolicy.InstanceRefresh(new InstanceRefreshOptions {
Strategy = InstanceRefreshStrategy.ROLLING,
MinHealthyPercentage = 90,
MaxHealthyPercentage = 100,
InstanceWarmup = Duration.Seconds(300),
CheckpointPercentages = new [] { 50, 100 },
CheckpointDelay = Duration.Minutes(10),
Alarms = new [] { alarm }
})
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
var alarm Alarm
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
UpdatePolicy: autoscaling.UpdatePolicy_InstanceRefresh(&InstanceRefreshOptions{
Strategy: autoscaling.InstanceRefreshStrategy_ROLLING,
MinHealthyPercentage: jsii.Number(90),
MaxHealthyPercentage: jsii.Number(100),
InstanceWarmup: awscdk.Duration_Seconds(jsii.Number(300)),
CheckpointPercentages: []*f64{
jsii.Number(50),
jsii.Number(100),
},
CheckpointDelay: awscdk.Duration_Minutes(jsii.Number(10)),
Alarms: []IAlarmRef{
alarm,
},
}),
})
Note: CloudFormation reads the
UpdatePolicyfrom the rollback target template (the template being rolled back to), not from the template that triggered the update. Keep theupdatePolicyon the Auto Scaling group permanently — if you remove it after the triggering update, a subsequent rollback will not perform an instance refresh.
If you omit minHealthyPercentage/maxHealthyPercentage, they fall back to the Auto Scaling group's instance maintenance policy when one is defined; otherwise CloudFormation defaults to 100/110 for the Rolling strategy (launch-before-terminate with a 10% surge) and 90/100 for ReplaceRootVolume.
Allowing Connections
See the documentation of the aws-cdk-lib/aws-ec2 package for more information about allowing connections between resources backed by instances.
Max Instance Lifetime
To enable the max instance lifetime support, specify maxInstanceLifetime 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.
Instance Monitoring
To disable detailed instance monitoring, specify instanceMonitoring property for the AutoscalingGroup resource as Monitoring.BASIC. Otherwise detailed monitoring will be enabled.
Monitoring Group Metrics
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 groupMetrics 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 groupMetrics property:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
// Enable monitoring of all group metrics
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
groupMetrics: [autoscaling.GroupMetrics.all()],
});
// Enable monitoring for a subset of group metrics
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
groupMetrics: [new autoscaling.GroupMetrics(autoscaling.GroupMetric.MIN_SIZE, autoscaling.GroupMetric.MAX_SIZE)],
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
# Enable monitoring of all group metrics
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
group_metrics=[autoscaling.GroupMetrics.all()]
)
# Enable monitoring for a subset of group metrics
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
group_metrics=[autoscaling.GroupMetrics(autoscaling.GroupMetric.MIN_SIZE, autoscaling.GroupMetric.MAX_SIZE)]
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
// Enable monitoring of all group metrics
// Enable monitoring of all group metrics
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.groupMetrics(List.of(GroupMetrics.all()))
.build();
// Enable monitoring for a subset of group metrics
// Enable monitoring for a subset of group metrics
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.groupMetrics(List.of(new GroupMetrics(GroupMetric.MIN_SIZE, GroupMetric.MAX_SIZE)))
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
// Enable monitoring of all group metrics
// Enable monitoring of all group metrics
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
GroupMetrics = new [] { GroupMetrics.All() }
});
// Enable monitoring for a subset of group metrics
// Enable monitoring for a subset of group metrics
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
GroupMetrics = new [] { new GroupMetrics(GroupMetric.MIN_SIZE, GroupMetric.MAX_SIZE) }
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
// Enable monitoring of all group metrics
// Enable monitoring of all group metrics
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
GroupMetrics: []GroupMetrics{
autoscaling.GroupMetrics_All(),
},
})
// Enable monitoring for a subset of group metrics
// Enable monitoring for a subset of group metrics
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
GroupMetrics: []GroupMetrics{
autoscaling.NewGroupMetrics(autoscaling.GroupMetric_MIN_SIZE(), autoscaling.GroupMetric_MAX_SIZE()),
},
})
Termination policies
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 terminationPolicies 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 terminationPolicyCustomLambdaFunctionArn 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.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
declare const arn: string;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
terminationPolicies: [
autoscaling.TerminationPolicy.CUSTOM_LAMBDA_FUNCTION,
autoscaling.TerminationPolicy.OLDEST_INSTANCE,
autoscaling.TerminationPolicy.DEFAULT,
],
//terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
terminationPolicyCustomLambdaFunctionArn: arn,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
# arn: str
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
termination_policies=[autoscaling.TerminationPolicy.CUSTOM_LAMBDA_FUNCTION, autoscaling.TerminationPolicy.OLDEST_INSTANCE, autoscaling.TerminationPolicy.DEFAULT
],
# terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
termination_policy_custom_lambda_function_arn=arn
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
String arn;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.terminationPolicies(List.of(TerminationPolicy.CUSTOM_LAMBDA_FUNCTION, TerminationPolicy.OLDEST_INSTANCE, TerminationPolicy.DEFAULT))
//terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
.terminationPolicyCustomLambdaFunctionArn(arn)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
string arn;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
TerminationPolicies = new [] { TerminationPolicy.CUSTOM_LAMBDA_FUNCTION, TerminationPolicy.OLDEST_INSTANCE, TerminationPolicy.DEFAULT },
//terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
TerminationPolicyCustomLambdaFunctionArn = arn
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
var arn string
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
TerminationPolicies: []TerminationPolicy{
autoscaling.TerminationPolicy_CUSTOM_LAMBDA_FUNCTION,
autoscaling.TerminationPolicy_OLDEST_INSTANCE,
autoscaling.TerminationPolicy_DEFAULT,
},
//terminationPolicyCustomLambdaFunctionArn property must be specified if the TerminationPolicy.CUSTOM_LAMBDA_FUNCTION is used
TerminationPolicyCustomLambdaFunctionArn: arn,
})
Protecting new instances from being terminated on scale-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. EC2 Capacity Providers for Amazon ECS requires this attribute be set to true.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
newInstancesProtectedFromScaleIn: true,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
new_instances_protected_from_scale_in=True
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.newInstancesProtectedFromScaleIn(true)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
NewInstancesProtectedFromScaleIn = true
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
NewInstancesProtectedFromScaleIn: jsii.Boolean(true),
})
Configuring Capacity Rebalancing
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.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
capacityRebalance: true,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
capacity_rebalance=True
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.capacityRebalance(true)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
CapacityRebalance = true
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
CapacityRebalance: jsii.Boolean(true),
})
Connecting to your instances using SSM Session Manager
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:
- Use an image with SSM agent installed and configured. Many images come with SSM Agent preinstalled, otherwise you may need to manually put instructions to install SSM Agent into your instance's UserData or use EC2 Init).
- Create the AutoScalingGroup with
ssmSessionPermissions: true.
If these conditions are met, you can connect to the instance from the EC2 Console. Example:
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
// Amazon Linux 2 comes with SSM Agent by default
machineImage: ec2.MachineImage.latestAmazonLinux2(),
// Turn on SSM
ssmSessionPermissions: true,
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
# Amazon Linux 2 comes with SSM Agent by default
machine_image=ec2.MachineImage.latest_amazon_linux2(),
# Turn on SSM
ssm_session_permissions=True
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.T3, InstanceSize.MICRO))
// Amazon Linux 2 comes with SSM Agent by default
.machineImage(MachineImage.latestAmazonLinux2())
// Turn on SSM
.ssmSessionPermissions(true)
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.T3, InstanceSize.MICRO),
// Amazon Linux 2 comes with SSM Agent by default
MachineImage = MachineImage.LatestAmazonLinux2(),
// Turn on SSM
SsmSessionPermissions = true
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_T3, ec2.InstanceSize_MICRO),
// Amazon Linux 2 comes with SSM Agent by default
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
// Turn on SSM
SsmSessionPermissions: jsii.Boolean(true),
})
Configuring Instance Metadata Service (IMDS)
Toggling IMDSv1
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 requireImdsv2 property. The example below demonstrates IMDSv2 being required on a single AutoScalingGroup:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
requireImdsv2: true,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
require_imdsv2=True
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.requireImdsv2(true)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
RequireImdsv2 = true
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
RequireImdsv2: jsii.Boolean(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:
const aspect = new autoscaling.AutoScalingGroupRequireImdsv2Aspect();
Aspects.of(this).add(aspect);
aspect = autoscaling.AutoScalingGroupRequireImdsv2Aspect()
Aspects.of(self).add(aspect)
AutoScalingGroupRequireImdsv2Aspect aspect = new AutoScalingGroupRequireImdsv2Aspect();
Aspects.of(this).add(aspect);
var aspect = new AutoScalingGroupRequireImdsv2Aspect();
Aspects.Of(this).Add(aspect);
aspect := autoscaling.NewAutoScalingGroupRequireImdsv2Aspect()
awscdk.Aspects_Of(this).Add(aspect)
Warm Pool
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:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.addWarmPool();
# auto_scaling_group: autoscaling.AutoScalingGroup
auto_scaling_group.add_warm_pool()
AutoScalingGroup autoScalingGroup;
autoScalingGroup.addWarmPool();
AutoScalingGroup autoScalingGroup;
autoScalingGroup.AddWarmPool();
var autoScalingGroup AutoScalingGroup
autoScalingGroup.addWarmPool()
You can also customize a warm pool by configuring parameters:
declare const autoScalingGroup: autoscaling.AutoScalingGroup;
autoScalingGroup.addWarmPool({
minSize: 1,
reuseOnScaleIn: true,
});
# auto_scaling_group: autoscaling.AutoScalingGroup
auto_scaling_group.add_warm_pool(
min_size=1,
reuse_on_scale_in=True
)
AutoScalingGroup autoScalingGroup;
autoScalingGroup.addWarmPool(WarmPoolOptions.builder()
.minSize(1)
.reuseOnScaleIn(true)
.build());
AutoScalingGroup autoScalingGroup;
autoScalingGroup.AddWarmPool(new WarmPoolOptions {
MinSize = 1,
ReuseOnScaleIn = true
});
var autoScalingGroup AutoScalingGroup
autoScalingGroup.addWarmPool(&WarmPoolOptions{
MinSize: jsii.Number(1),
ReuseOnScaleIn: jsii.Boolean(true),
})
Default Instance Warming
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
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
defaultInstanceWarmup: Duration.seconds(5),
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
default_instance_warmup=Duration.seconds(5)
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.defaultInstanceWarmup(Duration.seconds(5))
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
DefaultInstanceWarmup = Duration.Seconds(5)
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
DefaultInstanceWarmup: awscdk.Duration_Seconds(jsii.Number(5)),
})
Configuring KeyPair for instances
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 keyPair as a prop:
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
const myKeyPair = new ec2.KeyPair(this, 'MyKeyPair');
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
keyPair: myKeyPair,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
my_key_pair = ec2.KeyPair(self, "MyKeyPair")
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
key_pair=my_key_pair
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
KeyPair myKeyPair = new KeyPair(this, "MyKeyPair");
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.keyPair(myKeyPair)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
var myKeyPair = new KeyPair(this, "MyKeyPair");
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
KeyPair = myKeyPair
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
myKeyPair := ec2.NewKeyPair(this, jsii.String("MyKeyPair"))
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
KeyPair: myKeyPair,
})
Capacity Distribution Strategy
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.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// ...
azCapacityDistributionStrategy: autoscaling.CapacityDistributionStrategy.BALANCED_ONLY,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# ...
az_capacity_distribution_strategy=autoscaling.CapacityDistributionStrategy.BALANCED_ONLY
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// ...
.azCapacityDistributionStrategy(CapacityDistributionStrategy.BALANCED_ONLY)
.build();
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// ...
AzCapacityDistributionStrategy = CapacityDistributionStrategy.BALANCED_ONLY
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// ...
AzCapacityDistributionStrategy: autoscaling.CapacityDistributionStrategy_BALANCED_ONLY,
})
Deletion Protection
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.
declare const vpc: ec2.Vpc;
new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
machineImage: ec2.MachineImage.latestAmazonLinux2(),
deletionProtection: autoscaling.DeletionProtection.PREVENT_ALL_DELETION,
});
# vpc: ec2.Vpc
autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2(),
deletion_protection=autoscaling.DeletionProtection.PREVENT_ALL_DELETION
)
Vpc vpc;
AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.T3, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2())
.deletionProtection(DeletionProtection.PREVENT_ALL_DELETION)
.build();
Vpc vpc;
new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.T3, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2(),
DeletionProtection = DeletionProtection.PREVENT_ALL_DELETION
});
var vpc Vpc
autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_T3, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2(),
DeletionProtection: 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.
Instance Lifecycle Policy
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.
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;
const asg = new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,
// Configure instance lifecycle policy
instanceLifecyclePolicy: {
retentionTriggers: {
terminateHookAbandon: autoscaling.TerminateHookAbandonAction.RETAIN,
},
},
});
// Add termination lifecycle hook (required for the policy to take effect)
asg.addLifecycleHook('TerminationHook', {
lifecycleTransition: autoscaling.LifecycleTransition.INSTANCE_TERMINATING,
});
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage
asg = autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=instance_type,
machine_image=machine_image,
# Configure instance lifecycle policy
instance_lifecycle_policy=autoscaling.InstanceLifecyclePolicy(
retention_triggers=autoscaling.RetentionTriggers(
terminate_hook_abandon=autoscaling.TerminateHookAbandonAction.RETAIN
)
)
)
# Add termination lifecycle hook (required for the policy to take effect)
asg.add_lifecycle_hook("TerminationHook",
lifecycle_transition=autoscaling.LifecycleTransition.INSTANCE_TERMINATING
)
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
AutoScalingGroup asg = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(instanceType)
.machineImage(machineImage)
// Configure instance lifecycle policy
.instanceLifecyclePolicy(InstanceLifecyclePolicy.builder()
.retentionTriggers(RetentionTriggers.builder()
.terminateHookAbandon(TerminateHookAbandonAction.RETAIN)
.build())
.build())
.build();
// Add termination lifecycle hook (required for the policy to take effect)
asg.addLifecycleHook("TerminationHook", BasicLifecycleHookProps.builder()
.lifecycleTransition(LifecycleTransition.INSTANCE_TERMINATING)
.build());
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;
var asg = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = instanceType,
MachineImage = machineImage,
// Configure instance lifecycle policy
InstanceLifecyclePolicy = new InstanceLifecyclePolicy {
RetentionTriggers = new RetentionTriggers {
TerminateHookAbandon = TerminateHookAbandonAction.RETAIN
}
}
});
// Add termination lifecycle hook (required for the policy to take effect)
asg.AddLifecycleHook("TerminationHook", new BasicLifecycleHookProps {
LifecycleTransition = LifecycleTransition.INSTANCE_TERMINATING
});
var vpc Vpc
var instanceType InstanceType
var machineImage IMachineImage
asg := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: InstanceType,
MachineImage: MachineImage,
// Configure instance lifecycle policy
InstanceLifecyclePolicy: &InstanceLifecyclePolicy{
RetentionTriggers: &RetentionTriggers{
TerminateHookAbandon: autoscaling.TerminateHookAbandonAction_RETAIN,
},
},
})
// Add termination lifecycle hook (required for the policy to take effect)
asg.addLifecycleHook(jsii.String("TerminationHook"), &BasicLifecycleHookProps{
LifecycleTransition: autoscaling.LifecycleTransition_INSTANCE_TERMINATING,
})
The terminateHookAbandon 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.
Future work
- [ ] CloudWatch Events (impossible to add currently as the AutoScalingGroup ARN is necessary to make this rule and this cannot be accessed from CloudFormation).
Types
| Name | Kind | Summary |
|---|---|---|
AutoScalingGroup | Construct (L2) | A Fleet represents a managed set of EC2 instances. |
LifecycleHook | Construct (L2) | Define a life cycle hook. |
ScheduledAction | Construct (L2) | Define a scheduled scaling action. |
WarmPool | Construct (L2) | Define a warm pool. |
CfnAutoScalingGroup | Construct (L1) | The AWS::AutoScaling::AutoScalingGroup resource defines an Amazon EC2 Auto Scaling group, which is a collection of Amazon EC2 instances that are treated as a logical grouping for the purposes of automatic scaling and management. |
CfnLaunchConfiguration | Construct (L1) | The AWS::AutoScaling::LaunchConfiguration resource specifies the launch configuration that can be used by an Auto Scaling group to configure Amazon EC2 instances. |
CfnLifecycleHook | Construct (L1) | The AWS::AutoScaling::LifecycleHook resource specifies lifecycle hooks for an Auto Scaling group. |
CfnScalingPolicy | Construct (L1) | The AWS::AutoScaling::ScalingPolicy resource specifies an Amazon EC2 Auto Scaling scaling policy so that the Auto Scaling group can scale the number of instances available for your application. |
CfnScheduledAction | Construct (L1) | The AWS::AutoScaling::ScheduledAction resource specifies an Amazon EC2 Auto Scaling scheduled action so that the Auto Scaling group can change the number of instances available for your application in response to predictable load changes. |
CfnWarmPool | Construct (L1) | The AWS::AutoScaling::WarmPool resource creates a pool of pre-initialized EC2 instances that sits alongside the Auto Scaling group. |
AdditionalHealthChecksOptions | Struct | Additional Heath checks options. |
AdditionalHealthCheckType | Enum | Additional Health Check Type. |
AdjustmentTier | Struct | An adjustment. |
AdjustmentType | Enum | How adjustment numbers are interpreted. |
ApplyCloudFormationInitOptions | Struct | Options for applying CloudFormation init to an instance or instance group. |
AutoScalingGroupProps | Struct | Properties of a Fleet. |
AutoScalingGroupRequireImdsv2Aspect | Class | Aspect that makes IMDSv2 required on instances deployed by AutoScalingGroups. |
BaseTargetTrackingProps | Struct | Base interface for target tracking props. |
BasicLifecycleHookProps | Struct | Basic properties for a lifecycle hook. |
BasicScheduledActionProps | Struct | Properties for a scheduled scaling action. |
BasicStepScalingPolicyProps | Struct | |
BasicTargetTrackingScalingPolicyProps | Struct | Properties for a Target Tracking policy that include the metric but exclude the target. |
BindHookTargetOptions | Struct | Options needed to bind a target to a lifecycle hook. |
BlockDevice | Struct | Block device. |
BlockDeviceVolume | Class | Describes a block device mapping for an EC2 instance or Auto Scaling group. |
CapacityDistributionStrategy | Enum | The strategies for when launches fail in an Availability Zone. |
CfnAutoScalingGroup.AcceleratorCountRequestProperty | Struct | AcceleratorCountRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum number of accelerators for an instance type. |
CfnAutoScalingGroup.AcceleratorTotalMemoryMiBRequestProperty | Struct | AcceleratorTotalMemoryMiBRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum total memory size for the accelerators for an instance type, in MiB. |
CfnAutoScalingGroup.AvailabilityZoneDistributionProperty | Struct | AvailabilityZoneDistribution is a property of the AWS::AutoScaling::AutoScalingGroup resource. |
CfnAutoScalingGroup.AvailabilityZoneImpairmentPolicyProperty | Struct | Describes an Availability Zone impairment policy. |
CfnAutoScalingGroup.BaselineEbsBandwidthMbpsRequestProperty | Struct | BaselineEbsBandwidthMbpsRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum baseline bandwidth performance for an instance type, in Mbps. |
CfnAutoScalingGroup.BaselinePerformanceFactorsRequestProperty | Struct | The baseline performance to consider, using an instance family as a baseline reference. |
CfnAutoScalingGroup.CapacityReservationSpecificationProperty | Struct | Describes the Capacity Reservation preference and targeting options. |
CfnAutoScalingGroup.CapacityReservationTargetProperty | Struct | The target for the Capacity Reservation. |
CfnAutoScalingGroup.CpuPerformanceFactorRequestProperty | Struct | The CPU performance to consider, using an instance family as the baseline reference. |
CfnAutoScalingGroup.DistributionSegmentProperty | Struct | Use this structure to specify the capacity types that Amazon EC2 Auto Scaling prioritizes when it launches instances. |
CfnAutoScalingGroup.InstanceLifecyclePolicyProperty | Struct | The instance lifecycle policy for the Auto Scaling group. |
CfnAutoScalingGroup.InstanceMaintenancePolicyProperty | Struct | InstanceMaintenancePolicy is a property of the AWS::AutoScaling::AutoScalingGroup resource. |
CfnAutoScalingGroup.InstanceRequirementsProperty | Struct | The attributes for the instance types for a mixed instances policy. |
CfnAutoScalingGroup.InstancesDistributionProperty | Struct | Use this structure to specify the distribution of On-Demand Instances and Spot Instances and the allocation strategies used to fulfill On-Demand and Spot capacities for a mixed instances policy. |
CfnAutoScalingGroup.LaunchTemplateOverridesProperty | Struct | Use this structure to let Amazon EC2 Auto Scaling do the following when the Auto Scaling group has a mixed instances policy: - Override the instance type that is specified in the launch template. |
CfnAutoScalingGroup.LaunchTemplateProperty | Struct | Use this structure to specify the launch templates and instance types (overrides) for a mixed instances policy. |
CfnAutoScalingGroup.LaunchTemplateSpecificationProperty | Struct | Specifies a launch template to use when provisioning EC2 instances for an Auto Scaling group. |
CfnAutoScalingGroup.LifecycleHookSpecificationProperty | Struct | LifecycleHookSpecification specifies a lifecycle hook for the LifecycleHookSpecificationList property of the AWS::AutoScaling::AutoScalingGroup resource. A lifecycle hook specifies actions to perform when Amazon EC2 Auto Scaling launches or terminates instances. |
CfnAutoScalingGroup.MemoryGiBPerVCpuRequestProperty | Struct | MemoryGiBPerVCpuRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum amount of memory per vCPU for an instance type, in GiB. |
CfnAutoScalingGroup.MemoryMiBRequestProperty | Struct | MemoryMiBRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum instance memory size for an instance type, in MiB. |
CfnAutoScalingGroup.MetricsCollectionProperty | Struct | MetricsCollection is a property of the AWS::AutoScaling::AutoScalingGroup resource that describes the group metrics that an Amazon EC2 Auto Scaling group sends to Amazon CloudWatch. These metrics describe the group rather than any of its instances. |
CfnAutoScalingGroup.MixedInstancesPolicyProperty | Struct | Use this structure to launch multiple instance types and On-Demand Instances and Spot Instances within a single Auto Scaling group. |
CfnAutoScalingGroup.NetworkBandwidthGbpsRequestProperty | Struct | NetworkBandwidthGbpsRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum network bandwidth for an instance type, in Gbps. |
CfnAutoScalingGroup.NetworkInterfaceCountRequestProperty | Struct | NetworkInterfaceCountRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum number of network interfaces for an instance type. |
CfnAutoScalingGroup.NotificationConfigurationProperty | Struct | A structure that specifies an Amazon SNS notification configuration for the NotificationConfigurations property of the AWS::AutoScaling::AutoScalingGroup resource. |
CfnAutoScalingGroup.PerformanceFactorReferenceRequestProperty | Struct | Specify an instance family to use as the baseline reference for CPU performance. |
CfnAutoScalingGroup.RetentionTriggersProperty | Struct | Defines the specific triggers that cause instances to be retained in a Retained state rather than terminated. |
CfnAutoScalingGroup.TagPropertyProperty | Struct | A structure that specifies a tag for the Tags property of AWS::AutoScaling::AutoScalingGroup resource. |
CfnAutoScalingGroup.TotalLocalStorageGBRequestProperty | Struct | TotalLocalStorageGBRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum total local storage size for an instance type, in GB. |
CfnAutoScalingGroup.TrafficSourceIdentifierProperty | Struct | Identifying information for a traffic source. |
CfnAutoScalingGroup.VCpuCountRequestProperty | Struct | VCpuCountRequest is a property of the InstanceRequirements property of the AWS::AutoScaling::AutoScalingGroup LaunchTemplateOverrides property type that describes the minimum and maximum number of vCPUs for an instance type. |
CfnAutoScalingGroupProps | Struct | Properties for defining a CfnAutoScalingGroup. |
CfnLaunchConfiguration.BlockDeviceMappingProperty | Struct | BlockDeviceMapping specifies a block device mapping for the BlockDeviceMappings property of the AWS::AutoScaling::LaunchConfiguration resource. |
CfnLaunchConfiguration.BlockDeviceProperty | Struct | BlockDevice is a property of the EBS property of the AWS::AutoScaling::LaunchConfiguration BlockDeviceMapping property type that describes an Amazon EBS volume. |
CfnLaunchConfiguration.MetadataOptionsProperty | Struct | MetadataOptions is a property of AWS::AutoScaling::LaunchConfiguration that describes metadata options for the instances. |
CfnLaunchConfigurationProps | Struct | Properties for defining a CfnLaunchConfiguration. |
CfnLifecycleHookProps | Struct | Properties for defining a CfnLifecycleHook. |
CfnScalingPolicy.CustomizedMetricSpecificationProperty | Struct | Contains customized metric specification information for a target tracking scaling policy for Amazon EC2 Auto Scaling. |
CfnScalingPolicy.MetricDataQueryProperty | Struct | The metric data to return. |
CfnScalingPolicy.MetricDimensionProperty | Struct | MetricDimension specifies a name/value pair that is part of the identity of a CloudWatch metric for the Dimensions property of the AWS::AutoScaling::ScalingPolicy CustomizedMetricSpecification property type. Duplicate dimensions are not allowed. |
CfnScalingPolicy.MetricProperty | Struct | Represents a specific metric. |
CfnScalingPolicy.MetricStatProperty | Struct | MetricStat is a property of the AWS::AutoScaling::ScalingPolicy MetricDataQuery property type. |
CfnScalingPolicy.PredefinedMetricSpecificationProperty | Struct | Contains predefined metric specification information for a target tracking scaling policy for Amazon EC2 Auto Scaling. |
CfnScalingPolicy.PredictiveScalingConfigurationProperty | Struct | PredictiveScalingConfiguration is a property of the AWS::AutoScaling::ScalingPolicy resource that specifies a predictive scaling policy for Amazon EC2 Auto Scaling. |
CfnScalingPolicy.PredictiveScalingCustomizedCapacityMetricProperty | Struct | Contains capacity metric information for the CustomizedCapacityMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.PredictiveScalingCustomizedLoadMetricProperty | Struct | Contains load metric information for the CustomizedLoadMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.PredictiveScalingCustomizedScalingMetricProperty | Struct | Contains scaling metric information for the CustomizedScalingMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.PredictiveScalingMetricSpecificationProperty | Struct | A structure that specifies a metric specification for the MetricSpecifications property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingConfiguration property type. |
CfnScalingPolicy.PredictiveScalingPredefinedLoadMetricProperty | Struct | Contains load metric information for the PredefinedLoadMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.PredictiveScalingPredefinedMetricPairProperty | Struct | Contains metric pair information for the PredefinedMetricPairSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.PredictiveScalingPredefinedScalingMetricProperty | Struct | Contains scaling metric information for the PredefinedScalingMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type. |
CfnScalingPolicy.StepAdjustmentProperty | Struct | StepAdjustment specifies a step adjustment for the StepAdjustments property of the AWS::AutoScaling::ScalingPolicy resource. |
CfnScalingPolicy.TargetTrackingConfigurationProperty | Struct | TargetTrackingConfiguration is a property of the AWS::AutoScaling::ScalingPolicy resource that specifies a target tracking scaling policy configuration for Amazon EC2 Auto Scaling. |
CfnScalingPolicy.TargetTrackingMetricDataQueryProperty | Struct | The metric data to return. |
CfnScalingPolicy.TargetTrackingMetricStatProperty | Struct | This structure defines the CloudWatch metric to return, along with the statistic and unit. |
CfnScalingPolicyProps | Struct | Properties for defining a CfnScalingPolicy. |
CfnScheduledActionProps | Struct | Properties for defining a CfnScheduledAction. |
CfnWarmPool.InstanceReusePolicyProperty | Struct | A structure that specifies an instance reuse policy for the InstanceReusePolicy property of the AWS::AutoScaling::WarmPool resource. |
CfnWarmPoolProps | Struct | Properties for defining a CfnWarmPool. |
CommonAutoScalingGroupProps | Struct | Basic properties of an AutoScalingGroup, except the exact machines to run and where they should run. |
CpuUtilizationScalingProps | Struct | Properties for enabling scaling based on CPU utilization. |
CronOptions | Struct | Options to configure a cron expression. |
DefaultResult | Enum | |
DeletionProtection | Enum | Deletion protection level for Auto Scaling group. |
EbsDeviceOptions | Struct | Block device options for an EBS volume. |
EbsDeviceOptionsBase | Struct | Base block device options for an EBS volume. |
EbsDeviceProps | Struct | Properties of an EBS block device. |
EbsDeviceSnapshotOptions | Struct | Block device options for an EBS volume created from a snapshot. |
EbsDeviceVolumeType | Enum | Supported EBS volume types for blockDevices. |
Ec2HealthCheckOptions | Struct | EC2 Heath check options. |
Ec2HealthChecksOptions | Struct | EC2 Heath checks options. |
ElbHealthCheckOptions | Struct | ELB Heath check options. |
GroupMetric | Class | Group metrics that an Auto Scaling group sends to Amazon CloudWatch. |
GroupMetrics | Class | A set of group metrics. |
HealthCheck | Class | Health check settings. |
HealthChecks | Class | Health check settings for multiple types. |
IAutoScalingGroup | Interface | An AutoScalingGroup. |
ILifecycleHook | Interface | A basic lifecycle hook object. |
ILifecycleHookTarget | Interface | Interface for autoscaling lifecycle hook targets. |
InstanceLifecyclePolicy | Struct | Instance lifecycle policy for an Auto Scaling group. |
InstanceRefreshOptions | Struct | Options for customizing the instance refresh update policy. |
InstanceRefreshStrategy | Enum | The strategy to use for the instance refresh. |
InstancesDistribution | Struct | InstancesDistribution is a subproperty of MixedInstancesPolicy that describes an instances distribution for an Auto Scaling group. |
LaunchTemplateOverrides | Struct | LaunchTemplateOverrides is a subproperty of LaunchTemplate that describes an override for a launch template. |
LifecycleHookProps | Struct | Properties for a Lifecycle hook. |
LifecycleHookTargetConfig | Struct | Result of binding a lifecycle hook to a target. |
LifecycleTransition | Enum | What instance transition to attach the hook to. |
MetricAggregationType | Enum | How the scaling metric is going to be aggregated. |
MetricTargetTrackingProps | Struct | Properties for enabling tracking of an arbitrary metric. |
MixedInstancesPolicy | Struct | MixedInstancesPolicy allows you to configure a group that diversifies across On-Demand Instances and Spot Instances of multiple instance types. |
Monitoring | Enum | The monitoring mode for instances launched in an autoscaling group. |
NetworkUtilizationScalingProps | Struct | Properties for enabling scaling based on network utilization. |
NotificationConfiguration | Struct | AutoScalingGroup fleet change notifications configurations. |
OnDemandAllocationStrategy | Enum | Indicates how to allocate instance types to fulfill On-Demand capacity. |
PoolState | Enum | The instance state in the warm pool. |
PredefinedMetric | Enum | One of the predefined autoscaling metrics. |
RenderSignalsOptions | Struct | Input for Signals.renderCreationPolicy. |
RequestCountScalingProps | Struct | Properties for enabling scaling based on request/second. |
RetentionTriggers | Struct | Defines the specific triggers that cause instances to be retained in a Retained state rather than terminated. |
RollingUpdateOptions | Struct | Options for customizing the rolling update. |
ScaleInProtectedInstances | Enum | The behavior of instances that are protected from scale in during an instance refresh. |
ScalingEvent | Enum | Fleet scaling events. |
ScalingEvents | Class | A list of ScalingEvents, you can use one of the predefined lists, such as ScalingEvents.ERRORS or create a custom group by instantiating a NotificationTypes object, e.g: new NotificationTypes(NotificationType.INSTANCE_LAUNCH). |
ScalingInterval | Struct | A range of metric values in which to apply a certain scaling operation. |
ScalingProcess | Enum | |
Schedule | Class | Schedule for scheduled scaling actions. |
ScheduledActionProps | Struct | Properties for a scheduled action on an AutoScalingGroup. |
Signals | Class | Configure whether the AutoScalingGroup waits for signals. |
SignalsOptions | Struct | Customization options for Signal handling. |
SpotAllocationStrategy | Enum | Indicates how to allocate instance types to fulfill Spot capacity. |
StandbyInstances | Enum | The behavior of instances in standby during an instance refresh. |
StepScalingAction | Construct | Define a step scaling action. |
StepScalingActionProps | Struct | Properties for a scaling policy. |
StepScalingPolicy | Construct | Define a acaling strategy which scales depending on absolute values of some metric. |
StepScalingPolicyProps | Struct | |
TargetTrackingScalingPolicy | Construct | |
TargetTrackingScalingPolicyProps | Struct | Properties for a concrete TargetTrackingPolicy. |
TerminateHookAbandonAction | Enum | Actions for when a termination lifecycle hook is abandoned. |
TerminationPolicy | Enum | Specifies the termination criteria to apply before Amazon EC2 Auto Scaling chooses an instance for termination. |
UpdatePolicy | Class | How existing instances should be updated. |
WarmPoolOptions | Struct | Options for a warm pool. |
WarmPoolProps | Struct | Properties for a warm pool. |