Skip to content
v2.274.0

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:

ts
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(),
});
python
# 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()
)
java
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();
csharp
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()
});
go
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.

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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:

ts
declare const vpc: ec2.Vpc;
declare const launchTemplate: ec2.LaunchTemplate;

new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  launchTemplate: launchTemplate
});
python
# vpc: ec2.Vpc
# launch_template: ec2.LaunchTemplate


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    launch_template=launch_template
)
java
Vpc vpc;
LaunchTemplate launchTemplate;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .launchTemplate(launchTemplate)
        .build();
csharp
Vpc vpc;
LaunchTemplate launchTemplate;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    LaunchTemplate = launchTemplate
});
go
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:

ts
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 },
    ],
  }
});
python
# 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)]
    )
)
java
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();
csharp
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 } }
    }
});
go
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:

ts
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'],
        },
      }
    ],
  }
});
python
# 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"]
            )
        )
        ]
    )
)
java
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();
csharp
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" }
            }
        } }
    }
});
go
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:

ts
// 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',
  // ...
});
python
# 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"
})
java
// 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"));
csharp
// 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" }
});
go
// 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 the context section of your cdk.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:

ts
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(...);
python
# 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
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        .minCapacity(5)
        .maxCapacity(100)
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    MinCapacity = 5,
    MaxCapacity = 100
});
go
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:

plaintext
 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:

ts
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,
});
python
# 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
)
java
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());
csharp
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
});
go
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:

ts
declare const autoScalingGroup: autoscaling.AutoScalingGroup;

autoScalingGroup.scaleOnCpuUtilization('KeepSpareCPU', {
  targetUtilizationPercent: 50
});
python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_cpu_utilization("KeepSpareCPU",
    target_utilization_percent=50
)
java
AutoScalingGroup autoScalingGroup;


autoScalingGroup.scaleOnCpuUtilization("KeepSpareCPU", CpuUtilizationScalingProps.builder()
        .targetUtilizationPercent(50)
        .build());
csharp
AutoScalingGroup autoScalingGroup;


autoScalingGroup.ScaleOnCpuUtilization("KeepSpareCPU", new CpuUtilizationScalingProps {
    TargetUtilizationPercent = 50
});
go
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:

ts
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
});
python
# 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
)
java
AutoScalingGroup autoScalingGroup;


autoScalingGroup.scaleOnIncomingBytes("LimitIngressPerInstance", NetworkUtilizationScalingProps.builder()
        .targetBytesPerSecond(10 * 1024 * 1024)
        .build());
autoScalingGroup.scaleOnOutgoingBytes("LimitEgressPerInstance", NetworkUtilizationScalingProps.builder()
        .targetBytesPerSecond(10 * 1024 * 1024)
        .build());
csharp
AutoScalingGroup autoScalingGroup;


autoScalingGroup.ScaleOnIncomingBytes("LimitIngressPerInstance", new NetworkUtilizationScalingProps {
    TargetBytesPerSecond = 10 * 1024 * 1024
});
autoScalingGroup.ScaleOnOutgoingBytes("LimitEgressPerInstance", new NetworkUtilizationScalingProps {
    TargetBytesPerSecond = 10 * 1024 * 1024
});
go
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):

ts
declare const autoScalingGroup: autoscaling.AutoScalingGroup;

autoScalingGroup.scaleOnRequestCount('LimitRPS', {
    targetRequestsPerSecond: 1000
});
python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_request_count("LimitRPS",
    target_requests_per_second=1000
)
java
AutoScalingGroup autoScalingGroup;


autoScalingGroup.scaleOnRequestCount("LimitRPS", RequestCountScalingProps.builder()
        .targetRequestsPerSecond(1000)
        .build());
csharp
AutoScalingGroup autoScalingGroup;


autoScalingGroup.ScaleOnRequestCount("LimitRPS", new RequestCountScalingProps {
    TargetRequestsPerSecond = 1000
});
go
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 minCapacity high or the maxCapacity low.
  • Still allow the regular scaling actions to do their job, but restrict the range they can scale over (by setting both minCapacity and maxCapacity but changing their range over time).

A schedule is expressed as a cron expression. The Schedule class has a cron method to help build cron expressions.

The following example scales the fleet out in the morning, going back to natural scaling (all the way down to 1 instance if necessary) at night:

ts
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
});
python
# 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
)
java
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());
csharp
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
});
go
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:

ts
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),
  }),
});
python
# 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)
    )
)
java
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();
csharp
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)
    })
});
go
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.

ts
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,
    ],
  }),
});
python
# 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
        ]
    )
)
java
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();
csharp
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 }
    })
});
go
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.

ts
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,
});
python
# 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
)
java
Vpc vpc;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
        .machineImage(MachineImage.latestAmazonLinux2())
        .maxHealthyPercentage(200)
        .minHealthyPercentage(100)
        .build();
csharp
Vpc vpc;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
    MachineImage = MachineImage.LatestAmazonLinux2(),
    MaxHealthyPercentage = 200,
    MinHealthyPercentage = 100
});
go
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.

ts
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,
        }),
      },
  ],
  // ...
});
python
# 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
        )
    )
    ]
)
java
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();
csharp
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
        })
    } }
});
go
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 signals to configure how long CloudFormation should wait for the instances to successfully configure themselves.
  • you should also specify an updatePolicy to configure how instances should be updated when the AutoScalingGroup is updated (for example, when the AMI is updated). If you don't specify an update policy, a rolling update is chosen by default.

Here's an example of using CloudFormation Init to write a file to the instance hosts on startup:

ts
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),
  }),
});
python
# 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)
    )
)
java
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();
csharp
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)
    })
});
go
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 of desiredCapacity amount of instances to have started (recommended).
  • Signals.waitForMinCapacity([options]): wait for a minCapacity amount of instances to have started (use this if waiting for all instances takes too long and you are happy with a minimum count of healthy hosts).
  • Signals.waitForCount(count, [options]): wait for a specific amount of instances to have started.

There are two options you can configure:

  • timeout: maximum time a host startup is allowed to take. If a host does not report success within this time, it is considered a failure. Default is 5 minutes.
  • 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, if signals is configured on the AutoScalingGroup), the old AutoScalingGroup is deleted. If the deployment needs to be rolled back, the new AutoScalingGroup is deleted and the old one is left unchanged.
  • 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:

ts
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],
  }),
});
python
# 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]
    )
)
java
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();
csharp
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 }
    })
});
go
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 UpdatePolicy from the rollback target template (the template being rolled back to), not from the template that triggered the update. Keep the updatePolicy on 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:

ts
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)],
});
python
# 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)]
)
java
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();
csharp
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) }
});
go
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.

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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.

ts
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,
});
python
# 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
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        // ...

        .newInstancesProtectedFromScaleIn(true)
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    // ...

    NewInstancesProtectedFromScaleIn = true
});
go
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.

ts
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,
});
python
# 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
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        // ...

        .capacityRebalance(true)
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    // ...

    CapacityRebalance = true
});
go
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:

If these conditions are met, you can connect to the instance from the EC2 Console. Example:

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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:

ts
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,
});
python
# 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
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        // ...

        .requireImdsv2(true)
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    // ...

    RequireImdsv2 = true
});
go
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:

ts
const aspect = new autoscaling.AutoScalingGroupRequireImdsv2Aspect();

Aspects.of(this).add(aspect);
python
aspect = autoscaling.AutoScalingGroupRequireImdsv2Aspect()

Aspects.of(self).add(aspect)
java
AutoScalingGroupRequireImdsv2Aspect aspect = new AutoScalingGroupRequireImdsv2Aspect();

Aspects.of(this).add(aspect);
csharp
var aspect = new AutoScalingGroupRequireImdsv2Aspect();

Aspects.Of(this).Add(aspect);
go
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:

ts
declare const autoScalingGroup: autoscaling.AutoScalingGroup;

autoScalingGroup.addWarmPool();
python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.add_warm_pool()
java
AutoScalingGroup autoScalingGroup;


autoScalingGroup.addWarmPool();
csharp
AutoScalingGroup autoScalingGroup;


autoScalingGroup.AddWarmPool();
go
var autoScalingGroup AutoScalingGroup


autoScalingGroup.addWarmPool()

You can also customize a warm pool by configuring parameters:

ts
declare const autoScalingGroup: autoscaling.AutoScalingGroup;

autoScalingGroup.addWarmPool({
  minSize: 1,
  reuseOnScaleIn: true,
});
python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.add_warm_pool(
    min_size=1,
    reuse_on_scale_in=True
)
java
AutoScalingGroup autoScalingGroup;


autoScalingGroup.addWarmPool(WarmPoolOptions.builder()
        .minSize(1)
        .reuseOnScaleIn(true)
        .build());
csharp
AutoScalingGroup autoScalingGroup;


autoScalingGroup.AddWarmPool(new WarmPoolOptions {
    MinSize = 1,
    ReuseOnScaleIn = true
});
go
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

ts
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),
});
python
# 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)
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        // ...

        .defaultInstanceWarmup(Duration.seconds(5))
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    // ...

    DefaultInstanceWarmup = Duration.Seconds(5)
});
go
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:

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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.
ts
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,
});
python
# 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
)
java
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(instanceType)
        .machineImage(machineImage)

        // ...

        .azCapacityDistributionStrategy(CapacityDistributionStrategy.BALANCED_ONLY)
        .build();
csharp
Vpc vpc;
InstanceType instanceType;
IMachineImage machineImage;


new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = instanceType,
    MachineImage = machineImage,

    // ...

    AzCapacityDistributionStrategy = CapacityDistributionStrategy.BALANCED_ONLY
});
go
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.

ts
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,
});
python
# 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
)
java
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();
csharp
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
});
go
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.

ts
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,
});
python
# 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
)
java
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());
csharp
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
});
go
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 investigation
  • TERMINATE - 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 ​

NameKindSummary
AutoScalingGroupConstruct (L2)A Fleet represents a managed set of EC2 instances.
LifecycleHookConstruct (L2)Define a life cycle hook.
ScheduledActionConstruct (L2)Define a scheduled scaling action.
WarmPoolConstruct (L2)Define a warm pool.
CfnAutoScalingGroupConstruct (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.
CfnLaunchConfigurationConstruct (L1)The AWS::AutoScaling::LaunchConfiguration resource specifies the launch configuration that can be used by an Auto Scaling group to configure Amazon EC2 instances.
CfnLifecycleHookConstruct (L1)The AWS::AutoScaling::LifecycleHook resource specifies lifecycle hooks for an Auto Scaling group.
CfnScalingPolicyConstruct (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.
CfnScheduledActionConstruct (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.
CfnWarmPoolConstruct (L1)The AWS::AutoScaling::WarmPool resource creates a pool of pre-initialized EC2 instances that sits alongside the Auto Scaling group.
AdditionalHealthChecksOptionsStructAdditional Heath checks options.
AdditionalHealthCheckTypeEnumAdditional Health Check Type.
AdjustmentTierStructAn adjustment.
AdjustmentTypeEnumHow adjustment numbers are interpreted.
ApplyCloudFormationInitOptionsStructOptions for applying CloudFormation init to an instance or instance group.
AutoScalingGroupPropsStructProperties of a Fleet.
AutoScalingGroupRequireImdsv2AspectClassAspect that makes IMDSv2 required on instances deployed by AutoScalingGroups.
BaseTargetTrackingPropsStructBase interface for target tracking props.
BasicLifecycleHookPropsStructBasic properties for a lifecycle hook.
BasicScheduledActionPropsStructProperties for a scheduled scaling action.
BasicStepScalingPolicyPropsStruct
BasicTargetTrackingScalingPolicyPropsStructProperties for a Target Tracking policy that include the metric but exclude the target.
BindHookTargetOptionsStructOptions needed to bind a target to a lifecycle hook.
BlockDeviceStructBlock device.
BlockDeviceVolumeClassDescribes a block device mapping for an EC2 instance or Auto Scaling group.
CapacityDistributionStrategyEnumThe strategies for when launches fail in an Availability Zone.
CfnAutoScalingGroup.AcceleratorCountRequestPropertyStructAcceleratorCountRequest 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.AcceleratorTotalMemoryMiBRequestPropertyStructAcceleratorTotalMemoryMiBRequest 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.AvailabilityZoneDistributionPropertyStructAvailabilityZoneDistribution is a property of the AWS::AutoScaling::AutoScalingGroup resource.
CfnAutoScalingGroup.AvailabilityZoneImpairmentPolicyPropertyStructDescribes an Availability Zone impairment policy.
CfnAutoScalingGroup.BaselineEbsBandwidthMbpsRequestPropertyStructBaselineEbsBandwidthMbpsRequest 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.BaselinePerformanceFactorsRequestPropertyStructThe baseline performance to consider, using an instance family as a baseline reference.
CfnAutoScalingGroup.CapacityReservationSpecificationPropertyStructDescribes the Capacity Reservation preference and targeting options.
CfnAutoScalingGroup.CapacityReservationTargetPropertyStructThe target for the Capacity Reservation.
CfnAutoScalingGroup.CpuPerformanceFactorRequestPropertyStructThe CPU performance to consider, using an instance family as the baseline reference.
CfnAutoScalingGroup.DistributionSegmentPropertyStructUse this structure to specify the capacity types that Amazon EC2 Auto Scaling prioritizes when it launches instances.
CfnAutoScalingGroup.InstanceLifecyclePolicyPropertyStructThe instance lifecycle policy for the Auto Scaling group.
CfnAutoScalingGroup.InstanceMaintenancePolicyPropertyStructInstanceMaintenancePolicy is a property of the AWS::AutoScaling::AutoScalingGroup resource.
CfnAutoScalingGroup.InstanceRequirementsPropertyStructThe attributes for the instance types for a mixed instances policy.
CfnAutoScalingGroup.InstancesDistributionPropertyStructUse 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.LaunchTemplateOverridesPropertyStructUse 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.LaunchTemplatePropertyStructUse this structure to specify the launch templates and instance types (overrides) for a mixed instances policy.
CfnAutoScalingGroup.LaunchTemplateSpecificationPropertyStructSpecifies a launch template to use when provisioning EC2 instances for an Auto Scaling group.
CfnAutoScalingGroup.LifecycleHookSpecificationPropertyStructLifecycleHookSpecification 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.MemoryGiBPerVCpuRequestPropertyStructMemoryGiBPerVCpuRequest 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.MemoryMiBRequestPropertyStructMemoryMiBRequest 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.MetricsCollectionPropertyStructMetricsCollection 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.MixedInstancesPolicyPropertyStructUse this structure to launch multiple instance types and On-Demand Instances and Spot Instances within a single Auto Scaling group.
CfnAutoScalingGroup.NetworkBandwidthGbpsRequestPropertyStructNetworkBandwidthGbpsRequest 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.NetworkInterfaceCountRequestPropertyStructNetworkInterfaceCountRequest 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.NotificationConfigurationPropertyStructA structure that specifies an Amazon SNS notification configuration for the NotificationConfigurations property of the AWS::AutoScaling::AutoScalingGroup resource.
CfnAutoScalingGroup.PerformanceFactorReferenceRequestPropertyStructSpecify an instance family to use as the baseline reference for CPU performance.
CfnAutoScalingGroup.RetentionTriggersPropertyStructDefines the specific triggers that cause instances to be retained in a Retained state rather than terminated.
CfnAutoScalingGroup.TagPropertyPropertyStructA structure that specifies a tag for the Tags property of AWS::AutoScaling::AutoScalingGroup resource.
CfnAutoScalingGroup.TotalLocalStorageGBRequestPropertyStructTotalLocalStorageGBRequest 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.TrafficSourceIdentifierPropertyStructIdentifying information for a traffic source.
CfnAutoScalingGroup.VCpuCountRequestPropertyStructVCpuCountRequest 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.
CfnAutoScalingGroupPropsStructProperties for defining a CfnAutoScalingGroup.
CfnLaunchConfiguration.BlockDeviceMappingPropertyStructBlockDeviceMapping specifies a block device mapping for the BlockDeviceMappings property of the AWS::AutoScaling::LaunchConfiguration resource.
CfnLaunchConfiguration.BlockDevicePropertyStructBlockDevice is a property of the EBS property of the AWS::AutoScaling::LaunchConfiguration BlockDeviceMapping property type that describes an Amazon EBS volume.
CfnLaunchConfiguration.MetadataOptionsPropertyStructMetadataOptions is a property of AWS::AutoScaling::LaunchConfiguration that describes metadata options for the instances.
CfnLaunchConfigurationPropsStructProperties for defining a CfnLaunchConfiguration.
CfnLifecycleHookPropsStructProperties for defining a CfnLifecycleHook.
CfnScalingPolicy.CustomizedMetricSpecificationPropertyStructContains customized metric specification information for a target tracking scaling policy for Amazon EC2 Auto Scaling.
CfnScalingPolicy.MetricDataQueryPropertyStructThe metric data to return.
CfnScalingPolicy.MetricDimensionPropertyStructMetricDimension 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.MetricPropertyStructRepresents a specific metric.
CfnScalingPolicy.MetricStatPropertyStructMetricStat is a property of the AWS::AutoScaling::ScalingPolicy MetricDataQuery property type.
CfnScalingPolicy.PredefinedMetricSpecificationPropertyStructContains predefined metric specification information for a target tracking scaling policy for Amazon EC2 Auto Scaling.
CfnScalingPolicy.PredictiveScalingConfigurationPropertyStructPredictiveScalingConfiguration is a property of the AWS::AutoScaling::ScalingPolicy resource that specifies a predictive scaling policy for Amazon EC2 Auto Scaling.
CfnScalingPolicy.PredictiveScalingCustomizedCapacityMetricPropertyStructContains capacity metric information for the CustomizedCapacityMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.PredictiveScalingCustomizedLoadMetricPropertyStructContains load metric information for the CustomizedLoadMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.PredictiveScalingCustomizedScalingMetricPropertyStructContains scaling metric information for the CustomizedScalingMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.PredictiveScalingMetricSpecificationPropertyStructA structure that specifies a metric specification for the MetricSpecifications property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingConfiguration property type.
CfnScalingPolicy.PredictiveScalingPredefinedLoadMetricPropertyStructContains load metric information for the PredefinedLoadMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.PredictiveScalingPredefinedMetricPairPropertyStructContains metric pair information for the PredefinedMetricPairSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.PredictiveScalingPredefinedScalingMetricPropertyStructContains scaling metric information for the PredefinedScalingMetricSpecification property of the AWS::AutoScaling::ScalingPolicy PredictiveScalingMetricSpecification property type.
CfnScalingPolicy.StepAdjustmentPropertyStructStepAdjustment specifies a step adjustment for the StepAdjustments property of the AWS::AutoScaling::ScalingPolicy resource.
CfnScalingPolicy.TargetTrackingConfigurationPropertyStructTargetTrackingConfiguration is a property of the AWS::AutoScaling::ScalingPolicy resource that specifies a target tracking scaling policy configuration for Amazon EC2 Auto Scaling.
CfnScalingPolicy.TargetTrackingMetricDataQueryPropertyStructThe metric data to return.
CfnScalingPolicy.TargetTrackingMetricStatPropertyStructThis structure defines the CloudWatch metric to return, along with the statistic and unit.
CfnScalingPolicyPropsStructProperties for defining a CfnScalingPolicy.
CfnScheduledActionPropsStructProperties for defining a CfnScheduledAction.
CfnWarmPool.InstanceReusePolicyPropertyStructA structure that specifies an instance reuse policy for the InstanceReusePolicy property of the AWS::AutoScaling::WarmPool resource.
CfnWarmPoolPropsStructProperties for defining a CfnWarmPool.
CommonAutoScalingGroupPropsStructBasic properties of an AutoScalingGroup, except the exact machines to run and where they should run.
CpuUtilizationScalingPropsStructProperties for enabling scaling based on CPU utilization.
CronOptionsStructOptions to configure a cron expression.
DefaultResultEnum
DeletionProtectionEnumDeletion protection level for Auto Scaling group.
EbsDeviceOptionsStructBlock device options for an EBS volume.
EbsDeviceOptionsBaseStructBase block device options for an EBS volume.
EbsDevicePropsStructProperties of an EBS block device.
EbsDeviceSnapshotOptionsStructBlock device options for an EBS volume created from a snapshot.
EbsDeviceVolumeTypeEnumSupported EBS volume types for blockDevices.
Ec2HealthCheckOptionsStructEC2 Heath check options.
Ec2HealthChecksOptionsStructEC2 Heath checks options.
ElbHealthCheckOptionsStructELB Heath check options.
GroupMetricClassGroup metrics that an Auto Scaling group sends to Amazon CloudWatch.
GroupMetricsClassA set of group metrics.
HealthCheckClassHealth check settings.
HealthChecksClassHealth check settings for multiple types.
IAutoScalingGroupInterfaceAn AutoScalingGroup.
ILifecycleHookInterfaceA basic lifecycle hook object.
ILifecycleHookTargetInterfaceInterface for autoscaling lifecycle hook targets.
InstanceLifecyclePolicyStructInstance lifecycle policy for an Auto Scaling group.
InstanceRefreshOptionsStructOptions for customizing the instance refresh update policy.
InstanceRefreshStrategyEnumThe strategy to use for the instance refresh.
InstancesDistributionStructInstancesDistribution is a subproperty of MixedInstancesPolicy that describes an instances distribution for an Auto Scaling group.
LaunchTemplateOverridesStructLaunchTemplateOverrides is a subproperty of LaunchTemplate that describes an override for a launch template.
LifecycleHookPropsStructProperties for a Lifecycle hook.
LifecycleHookTargetConfigStructResult of binding a lifecycle hook to a target.
LifecycleTransitionEnumWhat instance transition to attach the hook to.
MetricAggregationTypeEnumHow the scaling metric is going to be aggregated.
MetricTargetTrackingPropsStructProperties for enabling tracking of an arbitrary metric.
MixedInstancesPolicyStructMixedInstancesPolicy allows you to configure a group that diversifies across On-Demand Instances and Spot Instances of multiple instance types.
MonitoringEnumThe monitoring mode for instances launched in an autoscaling group.
NetworkUtilizationScalingPropsStructProperties for enabling scaling based on network utilization.
NotificationConfigurationStructAutoScalingGroup fleet change notifications configurations.
OnDemandAllocationStrategyEnumIndicates how to allocate instance types to fulfill On-Demand capacity.
PoolStateEnumThe instance state in the warm pool.
PredefinedMetricEnumOne of the predefined autoscaling metrics.
RenderSignalsOptionsStructInput for Signals.renderCreationPolicy.
RequestCountScalingPropsStructProperties for enabling scaling based on request/second.
RetentionTriggersStructDefines the specific triggers that cause instances to be retained in a Retained state rather than terminated.
RollingUpdateOptionsStructOptions for customizing the rolling update.
ScaleInProtectedInstancesEnumThe behavior of instances that are protected from scale in during an instance refresh.
ScalingEventEnumFleet scaling events.
ScalingEventsClassA 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).
ScalingIntervalStructA range of metric values in which to apply a certain scaling operation.
ScalingProcessEnum
ScheduleClassSchedule for scheduled scaling actions.
ScheduledActionPropsStructProperties for a scheduled action on an AutoScalingGroup.
SignalsClassConfigure whether the AutoScalingGroup waits for signals.
SignalsOptionsStructCustomization options for Signal handling.
SpotAllocationStrategyEnumIndicates how to allocate instance types to fulfill Spot capacity.
StandbyInstancesEnumThe behavior of instances in standby during an instance refresh.
StepScalingActionConstructDefine a step scaling action.
StepScalingActionPropsStructProperties for a scaling policy.
StepScalingPolicyConstructDefine a acaling strategy which scales depending on absolute values of some metric.
StepScalingPolicyPropsStruct
TargetTrackingScalingPolicyConstruct
TargetTrackingScalingPolicyPropsStructProperties for a concrete TargetTrackingPolicy.
TerminateHookAbandonActionEnumActions for when a termination lifecycle hook is abandoned.
TerminationPolicyEnumSpecifies the termination criteria to apply before Amazon EC2 Auto Scaling chooses an instance for termination.
UpdatePolicyClassHow existing instances should be updated.
WarmPoolOptionsStructOptions for a warm pool.
WarmPoolPropsStructProperties for a warm pool.