Skip to content
v2.274.0

AsgCapacityProvider ​

An Auto Scaling Group Capacity Provider.

This allows an ECS cluster to target a specific EC2 Auto Scaling Group for the placement of tasks. Optionally (and recommended), ECS can manage the number of instances in the ASG to fit the tasks, and can ensure that instances are not prematurely terminated while there are still tasks running on them.

Example ​

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

// Either add default capacity
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
});

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  instanceType: new ec2.InstanceType('t2.xlarge'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux(),
  // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
  // machineImage: EcsOptimizedImage.amazonLinux2(),
  desiredCapacity: 3,
  // ... other options here ...
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster",
    vpc=vpc
)

# Either add default capacity
cluster.add_capacity("DefaultAutoScalingGroupCapacity",
    instance_type=ec2.InstanceType("t2.xlarge")
)

# Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=ec2.InstanceType("t2.xlarge"),
    machine_image=ecs.EcsOptimizedImage.amazon_linux(),
    # Or use Amazon ECS-Optimized Amazon Linux 2 AMI
    # machineImage: EcsOptimizedImage.amazonLinux2(),
    desired_capacity=3
)

capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
    auto_scaling_group=auto_scaling_group
)
cluster.add_asg_capacity_provider(capacity_provider)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .vpc(vpc)
        .build();

// Either add default capacity
cluster.addCapacity("DefaultAutoScalingGroupCapacity", AddCapacityOptions.builder()
        .instanceType(new InstanceType("t2.xlarge"))
        .build());

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(new InstanceType("t2.xlarge"))
        .machineImage(EcsOptimizedImage.amazonLinux())
        // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
        // machineImage: EcsOptimizedImage.amazonLinux2(),
        .desiredCapacity(3)
        .build();

AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
        .autoScalingGroup(autoScalingGroup)
        .build();
cluster.addAsgCapacityProvider(capacityProvider);
csharp
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps {
    Vpc = vpc
});

// Either add default capacity
cluster.AddCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions {
    InstanceType = new InstanceType("t2.xlarge")
});

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = new InstanceType("t2.xlarge"),
    MachineImage = EcsOptimizedImage.AmazonLinux(),
    // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
    // machineImage: EcsOptimizedImage.amazonLinux2(),
    DesiredCapacity = 3
});

var capacityProvider = new AsgCapacityProvider(this, "AsgCapacityProvider", new AsgCapacityProviderProps {
    AutoScalingGroup = autoScalingGroup
});
cluster.AddAsgCapacityProvider(capacityProvider);
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

// Either add default capacity
cluster.AddCapacity(jsii.String("DefaultAutoScalingGroupCapacity"), &AddCapacityOptions{
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
})

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	Vpc: Vpc,
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux(),
	// Or use Amazon ECS-Optimized Amazon Linux 2 AMI
	// machineImage: EcsOptimizedImage.amazonLinux2(),
	DesiredCapacity: jsii.Number(3),
})

capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("AsgCapacityProvider"), &AsgCapacityProviderProps{
	AutoScalingGroup: AutoScalingGroup,
})
cluster.AddAsgCapacityProvider(capacityProvider)

Initializer ​

ts
new AsgCapacityProvider(scope: Construct, id: string, props: AsgCapacityProviderProps)
python
AsgCapacityProvider(scope: Construct, id: str, props: AsgCapacityProviderProps)
java
new AsgCapacityProvider(Construct scope, String id, AsgCapacityProviderProps props)
csharp
new AsgCapacityProvider(Construct scope, string id, AsgCapacityProviderProps props)
go
NewAsgCapacityProvider(Scope Construct, Id *string, Props AsgCapacityProviderProps)

Construct Props ​

autoScalingGroupIAutoScalingGroupauto_scaling_groupIAutoScalingGroupautoScalingGroupIAutoScalingGroupAutoScalingGroupIAutoScalingGroupAutoScalingGroupIAutoScalingGrouprequired#
The autoscaling group to add as a Capacity Provider.
notes

Warning: When passing an imported resource using AutoScalingGroup.fromAutoScalingGroupName along with enableManagedTerminationProtection: true, the AsgCapacityProvider construct will not be able to enforce the option newInstancesProtectedFromScaleIn of the AutoScalingGroup. In this case the constructor of AsgCapacityProvider will throw an exception.

capacityProviderNameoptionalstringcapacity_provider_nameoptionalstrcapacityProviderNameoptionalStringCapacityProviderNameoptionalstringCapacityProviderNameoptional*string#
The name of the capacity provider.

Default: CloudFormation-generated name

notes

If a name is specified, it cannot start with aws, ecs, or fargate. If no name is specified, a default name in the CFNStackName-CFNResourceName-RandomString format is used. If the stack name starts with aws, ecs, or fargate, a unique resource name is generated that starts with cp-.

enableManagedDrainingoptionalbooleanenable_managed_drainingoptionalboolenableManagedDrainingoptionalBooleanEnableManagedDrainingoptionalboolEnableManagedDrainingoptional*bool#
Managed instance draining facilitates graceful termination of Amazon ECS instances.

Default: CloudFormation implicitly enables managed draining when not specified.

notes

This allows your service workloads to stop safely and be rescheduled to non-terminating instances. Infrastructure maintenance and updates are performed without disruptions to workloads.

When undefined (recommended), CloudFormation will implicitly enable managed draining. Set to true for explicit enablement or false to explicitly disable this feature.

enableManagedScalingoptionalbooleanenable_managed_scalingoptionalboolenableManagedScalingoptionalBooleanEnableManagedScalingoptionalboolEnableManagedScalingoptional*bool= true#
When enabled the scale-in and scale-out actions of the cluster's Auto Scaling Group will be managed for you.
notes

This means your cluster will automatically scale instances based on the load your tasks put on the cluster. For more information, see Using Managed Scaling in the ECS Developer Guide.

enableManagedTerminationProtectionoptionalbooleanenable_managed_termination_protectionoptionalboolenableManagedTerminationProtectionoptionalBooleanEnableManagedTerminationProtectionoptionalboolEnableManagedTerminationProtectionoptional*bool= true#
When enabled the Auto Scaling Group will only terminate EC2 instances that no longer have running non-daemon tasks.
notes

Scale-in protection will be automatically enabled on instances. When all non-daemon tasks are stopped on an instance, ECS initiates the scale-in process and turns off scale-in protection for the instance. The Auto Scaling Group can then terminate the instance. For more information see Managed termination protection in the ECS Developer Guide.

Managed scaling must also be enabled.

instanceWarmupPeriodoptionalnumberinstance_warmup_periodoptionalint | floatinstanceWarmupPeriodoptionalNumberInstanceWarmupPeriodoptionaldoubleInstanceWarmupPeriodoptional*float64= 300#
The period of time, in seconds, after a newly launched Amazon EC2 instance can contribute to CloudWatch metrics for Auto Scaling group.

Must be between 0 and 10000.

machineImageTypeoptionalMachineImageTypemachine_image_typeoptionalMachineImageTypemachineImageTypeoptionalMachineImageTypeMachineImageTypeoptionalMachineImageTypeMachineImageTypeoptionalMachineImageType#
What type of machine image this is.

Default: Automatically determined from machineImage, if available, otherwise MachineImageType.AMAZON_LINUX_2.

notes

Depending on the setting, different UserData will automatically be added to the AutoScalingGroup to configure it properly for use with ECS.

If you create an AutoScalingGroup yourself and are adding it via addAutoScalingGroup(), you must specify this value. If you are adding an autoScalingGroup via addCapacity, this value will be determined from the machineImage you pass.

maximumScalingStepSizeoptionalnumbermaximum_scaling_step_sizeoptionalint | floatmaximumScalingStepSizeoptionalNumberMaximumScalingStepSizeoptionaldoubleMaximumScalingStepSizeoptional*float64= 1000#
Maximum scaling step size.

In most cases this should be left alone.

minimumScalingStepSizeoptionalnumberminimum_scaling_step_sizeoptionalint | floatminimumScalingStepSizeoptionalNumberMinimumScalingStepSizeoptionaldoubleMinimumScalingStepSizeoptional*float64= 1#
Minimum scaling step size.

In most cases this should be left alone.

spotInstanceDrainingoptionalbooleanspot_instance_drainingoptionalboolspotInstanceDrainingoptionalBooleanSpotInstanceDrainingoptionalboolSpotInstanceDrainingoptional*bool= false#
Specify whether to enable Automated Draining for Spot Instances running Amazon ECS Services.

For more information, see Using Spot Instances.

targetCapacityPercentoptionalnumbertarget_capacity_percentoptionalint | floattargetCapacityPercentoptionalNumberTargetCapacityPercentoptionaldoubleTargetCapacityPercentoptional*float64= 100#
Target capacity percent.

In most cases this should be left alone.

topicEncryptionKeyoptionalIKeytopic_encryption_keyoptionalIKeytopicEncryptionKeyoptionalIKeyTopicEncryptionKeyoptionalIKeyTopicEncryptionKeyoptionalIKey#
If `AddAutoScalingGroupCapacityOptions.taskDrainTime` is non-zero, then the ECS cluster creates an SNS Topic to as part of a system to drain instances of tasks when the instance is being shut down. If this property is provided, then this key will be used to encrypt the contents of that SNS Topic. See [SNS Data Encryption](https://docs.aws.amazon.com/sns/latest/dg/sns-data-encryption.html) for more information.

Default: The SNS Topic will not be encrypted.

Properties ​

autoScalingGroupAutoScalingGroupauto_scaling_groupAutoScalingGroupautoScalingGroupAutoScalingGroupAutoScalingGroupAutoScalingGroupAutoScalingGroupAutoScalingGrouprequired#
Auto Scaling Group.
capacityProviderNamestringcapacity_provider_namestrcapacityProviderNameStringCapacityProviderNamestringCapacityProviderName*stringrequired#
Capacity provider name.

Default: Chosen by CloudFormation

enableManagedDrainingmay be undefinedbooleanenable_managed_drainingmay be undefinedboolenableManagedDrainingmay be undefinedBooleanEnableManagedDrainingmay be undefinedboolEnableManagedDrainingmay be undefined*bool#
Whether managed draining is enabled.
enableManagedTerminationProtectionmay be undefinedbooleanenable_managed_termination_protectionmay be undefinedboolenableManagedTerminationProtectionmay be undefinedBooleanEnableManagedTerminationProtectionmay be undefinedboolEnableManagedTerminationProtectionmay be undefined*bool#
Whether managed termination protection is enabled.
machineImageTypeMachineImageTypemachine_image_typeMachineImageTypemachineImageTypeMachineImageTypeMachineImageTypeMachineImageTypeMachineImageTypeMachineImageTyperequired#
Auto Scaling Group machineImageType.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.

Methods ​

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining