Cluster L2 construct
A regional grouping of one or more container instances on which you can run tasks and services.
Example
declare const vpc: ec2.Vpc;
const cluster = new ecs.Cluster(this, 'Cluster', {
vpc,
});
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
minCapacity: 0,
maxCapacity: 100,
});
const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
autoScalingGroup,
instanceWarmupPeriod: 300,
});
cluster.addAsgCapacityProvider(capacityProvider);
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('web', {
image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
memoryReservationMiB: 256,
});
new ecs.Ec2Service(this, 'EC2Service', {
cluster,
taskDefinition,
minHealthyPercent: 100,
capacityProviderStrategies: [
{
capacityProvider: capacityProvider.capacityProviderName,
weight: 1,
},
],
});
# vpc: ec2.Vpc
cluster = ecs.Cluster(self, "Cluster",
vpc=vpc
)
auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
vpc=vpc,
instance_type=ec2.InstanceType("t2.micro"),
machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
min_capacity=0,
max_capacity=100
)
capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
auto_scaling_group=auto_scaling_group,
instance_warmup_period=300
)
cluster.add_asg_capacity_provider(capacity_provider)
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("web",
image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_reservation_mi_b=256
)
ecs.Ec2Service(self, "EC2Service",
cluster=cluster,
task_definition=task_definition,
min_healthy_percent=100,
capacity_provider_strategies=[ecs.CapacityProviderStrategy(
capacity_provider=capacity_provider.capacity_provider_name,
weight=1
)
]
)
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.build();
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(new InstanceType("t2.micro"))
.machineImage(EcsOptimizedImage.amazonLinux2())
.minCapacity(0)
.maxCapacity(100)
.build();
AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
.autoScalingGroup(autoScalingGroup)
.instanceWarmupPeriod(300)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryReservationMiB(256)
.build());
Ec2Service.Builder.create(this, "EC2Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider(capacityProvider.getCapacityProviderName())
.weight(1)
.build()))
.build();
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;
var cluster = new Cluster(this, "Cluster", new ClusterProps {
Vpc = vpc
});
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = new InstanceType("t2.micro"),
MachineImage = EcsOptimizedImage.AmazonLinux2(),
MinCapacity = 0,
MaxCapacity = 100
});
var capacityProvider = new AsgCapacityProvider(this, "AsgCapacityProvider", new AsgCapacityProviderProps {
AutoScalingGroup = autoScalingGroup,
InstanceWarmupPeriod = 300
});
cluster.AddAsgCapacityProvider(capacityProvider);
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryReservationMiB = 256
});
new Ec2Service(this, "EC2Service", new Ec2ServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
MinHealthyPercent = 100,
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = capacityProvider.CapacityProviderName,
Weight = 1
} }
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc Vpc
cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
Vpc: Vpc,
})
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
Vpc: Vpc,
InstanceType: ec2.NewInstanceType(jsii.String("t2.micro")),
MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(),
MinCapacity: jsii.Number(0),
MaxCapacity: jsii.Number(100),
})
capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("AsgCapacityProvider"), &AsgCapacityProviderProps{
AutoScalingGroup: AutoScalingGroup,
InstanceWarmupPeriod: jsii.Number(300),
})
cluster.AddAsgCapacityProvider(capacityProvider)
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
MemoryReservationMiB: jsii.Number(256),
})
ecs.NewEc2Service(this, jsii.String("EC2Service"), &Ec2ServiceProps{
Cluster: Cluster,
TaskDefinition: TaskDefinition,
MinHealthyPercent: jsii.Number(100),
CapacityProviderStrategies: []CapacityProviderStrategy{
&CapacityProviderStrategy{
CapacityProvider: capacityProvider.CapacityProviderName,
Weight: jsii.Number(1),
},
},
})
Initializer
new Cluster(scope: Construct, id: string, props?: ClusterProps)
Cluster(scope: Construct, id: str, props: typing.Optional[ClusterProps] = None)
new Cluster(Construct scope, String id, ClusterProps props)
new Cluster(Construct scope, string id, ClusterProps? props = null)
NewCluster(Scope Construct, Id *string, Props ClusterProps)
Construct Props
capacityoptionalAddCapacityOptionscapacityoptionalAddCapacityOptionscapacityoptionalAddCapacityOptionsCapacityoptionalAddCapacityOptionsCapacityoptionalAddCapacityOptions#Default: no EC2 capacity will be added, you can use addCapacity to add capacity later.
clusterNameoptionalstringcluster_nameoptionalstrclusterNameoptionalStringClusterNameoptionalstringClusterNameoptional*string#Default: CloudFormation-generated name
containerInsightsoptionalbooleancontainer_insightsoptionalboolcontainerInsightsoptionalBooleanContainerInsightsoptionalboolContainerInsightsoptional*booldeprecated#Default: Container Insights will be disabled for this cluster.
containerInsightsV2optionalContainerInsightscontainer_insights_v2optionalContainerInsightscontainerInsightsV2optionalContainerInsightsContainerInsightsV2optionalContainerInsightsContainerInsightsV2optionalContainerInsights#Default: {@link ContainerInsights.DISABLED } This may be overridden by ECS account level settings.
defaultCloudMapNamespaceoptionalCloudMapNamespaceOptionsdefault_cloud_map_namespaceoptionalCloudMapNamespaceOptionsdefaultCloudMapNamespaceoptionalCloudMapNamespaceOptionsDefaultCloudMapNamespaceoptionalCloudMapNamespaceOptionsDefaultCloudMapNamespaceoptionalCloudMapNamespaceOptions#Default: no service discovery namespace created, you can use addDefaultCloudMapNamespace to add a default service discovery namespace later.
enableFargateCapacityProvidersoptionalbooleanenable_fargate_capacity_providersoptionalboolenableFargateCapacityProvidersoptionalBooleanEnableFargateCapacityProvidersoptionalboolEnableFargateCapacityProvidersoptional*bool= false#executeCommandConfigurationoptionalExecuteCommandConfigurationexecute_command_configurationoptionalExecuteCommandConfigurationexecuteCommandConfigurationoptionalExecuteCommandConfigurationExecuteCommandConfigurationoptionalExecuteCommandConfigurationExecuteCommandConfigurationoptionalExecuteCommandConfiguration#Default: no configuration will be provided.
managedStorageConfigurationoptionalManagedStorageConfigurationmanaged_storage_configurationoptionalManagedStorageConfigurationmanagedStorageConfigurationoptionalManagedStorageConfigurationManagedStorageConfigurationoptionalManagedStorageConfigurationManagedStorageConfigurationoptionalManagedStorageConfiguration#Default: no encryption will be applied.
Properties
autoscalingGroupmay be undefinedIAutoScalingGroupautoscaling_groupmay be undefinedIAutoScalingGroupautoscalingGroupmay be undefinedIAutoScalingGroupAutoscalingGroupmay be undefinedIAutoScalingGroupAutoscalingGroupmay be undefinedIAutoScalingGroup#capacityProviderNamesstring[]capacity_provider_namestyping.List[str]capacityProviderNamesList<String>CapacityProviderNamesstring[]CapacityProviderNames*[]*stringrequired#clusterRefClusterReferencecluster_refClusterReferenceclusterRefClusterReferenceClusterRefClusterReferenceClusterRefClusterReferencerequired#clusterScopedCapacityProviderNamesstring[]cluster_scoped_capacity_provider_namestyping.List[str]clusterScopedCapacityProviderNamesList<String>ClusterScopedCapacityProviderNamesstring[]ClusterScopedCapacityProviderNames*[]*stringrequired#connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#defaultCapacityProviderStrategyCapacityProviderStrategy[]default_capacity_provider_strategytyping.List[CapacityProviderStrategy]defaultCapacityProviderStrategyList<CapacityProviderStrategy>DefaultCapacityProviderStrategyCapacityProviderStrategy[]DefaultCapacityProviderStrategy*[]CapacityProviderStrategyrequired#This is necessary to correctly create Capacity Provider Associations.
defaultCloudMapNamespacemay be undefinedINamespacedefault_cloud_map_namespacemay be undefinedINamespacedefaultCloudMapNamespacemay be undefinedINamespaceDefaultCloudMapNamespacemay be undefinedINamespaceDefaultCloudMapNamespacemay be undefinedINamespace#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
executeCommandConfigurationmay be undefinedExecuteCommandConfigurationexecute_command_configurationmay be undefinedExecuteCommandConfigurationexecuteCommandConfigurationmay be undefinedExecuteCommandConfigurationExecuteCommandConfigurationmay be undefinedExecuteCommandConfigurationExecuteCommandConfigurationmay be undefinedExecuteCommandConfiguration#grantsClusterGrantsgrantsClusterGrantsgrantsClusterGrantsGrantsClusterGrantsGrantsClusterGrantsrequired#hasEc2Capacitybooleanhas_ec2_capacityboolhasEc2CapacityBooleanHasEc2CapacityboolHasEc2Capacity*boolrequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#Methods
addAsgCapacityProvider(provider: AsgCapacityProvider, options?: AddAutoScalingGroupCapacityOptions): voiddef add_asg_capacity_provider(self, provider: AsgCapacityProvider, options: typing.Optional[AddAutoScalingGroupCapacityOptions] = None) -> Nonepublic void addAsgCapacityProvider(AsgCapacityProvider provider, AddAutoScalingGroupCapacityOptions options)public void AddAsgCapacityProvider(AsgCapacityProvider provider, AddAutoScalingGroupCapacityOptions? options = null)func AddAsgCapacityProvider(Provider AsgCapacityProvider, Options AddAutoScalingGroupCapacityOptions)#1 parameter
Parameters
providerproviderproviderproviderProvider— the capacity provider to add to this cluster.
addCapacity(id: string, options: AddCapacityOptions): AutoScalingGroupdef add_capacity(self, id: str, options: AddCapacityOptions) -> AutoScalingGrouppublic AutoScalingGroup addCapacity(String id, AddCapacityOptions options)public AutoScalingGroup AddCapacity(string id, AddCapacityOptions options)func AddCapacity(Id *string, Options AddCapacityOptions) AutoScalingGroup#This method adds compute capacity to a cluster by creating an AutoScalingGroup with the specified options.
Returns the AutoScalingGroup so you can add autoscaling settings to it.
addDefaultCapacityProviderStrategy(defaultCapacityProviderStrategy: CapacityProviderStrategy[]): voiddef add_default_capacity_provider_strategy(self, default_capacity_provider_strategy: typing.List[CapacityProviderStrategy]) -> Nonepublic void addDefaultCapacityProviderStrategy(List<CapacityProviderStrategy> defaultCapacityProviderStrategy)public void AddDefaultCapacityProviderStrategy(CapacityProviderStrategy[] defaultCapacityProviderStrategy)func AddDefaultCapacityProviderStrategy(DefaultCapacityProviderStrategy *[]CapacityProviderStrategy)#1 parameter
Parameters
defaultCapacityProviderStrategydefault_capacity_provider_strategydefaultCapacityProviderStrategydefaultCapacityProviderStrategyDefaultCapacityProviderStrategy— cluster default capacity provider strategy. This takes the form of a list of CapacityProviderStrategy objects.
addDefaultCloudMapNamespace(options: CloudMapNamespaceOptions): INamespacedef add_default_cloud_map_namespace(self, options: CloudMapNamespaceOptions) -> INamespacepublic INamespace addDefaultCloudMapNamespace(CloudMapNamespaceOptions options)public INamespace AddDefaultCloudMapNamespace(CloudMapNamespaceOptions options)func AddDefaultCloudMapNamespace(Options CloudMapNamespaceOptions) INamespace#notes
NOTE: HttpNamespaces are supported only for use cases involving Service Connect. For use cases involving both Service- Discovery and Service Connect, customers should manage the HttpNamespace outside of the Cluster.addDefaultCloudMapNamespace method.
addExistingDefaultCloudMapNamespace(options: ExistingCloudMapNamespaceOptions): INamespacedef add_existing_default_cloud_map_namespace(self, options: ExistingCloudMapNamespaceOptions) -> INamespacepublic INamespace addExistingDefaultCloudMapNamespace(ExistingCloudMapNamespaceOptions options)public INamespace AddExistingDefaultCloudMapNamespace(ExistingCloudMapNamespaceOptions options)func AddExistingDefaultCloudMapNamespace(Options ExistingCloudMapNamespaceOptions) INamespace#Unlike addDefaultCloudMapNamespace, this method does not create a new namespace; it registers a namespace that already exists (created elsewhere in the app or imported) as the cluster's default namespace.
addManagedInstancesCapacityProvider(provider: ManagedInstancesCapacityProvider): voiddef add_managed_instances_capacity_provider(self, provider: ManagedInstancesCapacityProvider) -> Nonepublic void addManagedInstancesCapacityProvider(ManagedInstancesCapacityProvider provider)public void AddManagedInstancesCapacityProvider(ManagedInstancesCapacityProvider provider)func AddManagedInstancesCapacityProvider(Provider ManagedInstancesCapacityProvider)#1 parameter
Parameters
providerproviderproviderproviderProvider— the capacity provider to add to this cluster.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
arnForTasks(keyPattern: string): stringdef arn_for_tasks(self, key_pattern: str) -> strpublic String arnForTasks(String keyPattern)public string ArnForTasks(string keyPattern)func ArnForTasks(KeyPattern *string) *string#To represent all tasks, specify "*".
1 parameter
Parameters
keyPatternkey_patternkeyPatternkeyPatternKeyPattern— Task id pattern.
enableFargateCapacityProviders(): voiddef enable_fargate_capacity_providers(self, ) -> Nonepublic void enableFargateCapacityProviders()public void EnableFargateCapacityProviders()func EnableFargateCapacityProviders()#fromClusterArn(scope: Construct, id: string, clusterArn: string): ICluster@staticmethod def from_cluster_arn(scope: Construct, id: str, cluster_arn: str) -> IClusterpublic static ICluster fromClusterArn(Construct scope, String id, String clusterArn)public static ICluster FromClusterArn(Construct scope, string id, string clusterArn)func FromClusterArn(Scope Construct, Id *string, ClusterArn *string) IClusterstatic#This does not provide access to the vpc, hasEc2Capacity, or connections - use the fromClusterAttributes method to access those properties.
fromClusterAttributes(scope: Construct, id: string, attrs: ClusterAttributes): ICluster@staticmethod def from_cluster_attributes(scope: Construct, id: str, attrs: ClusterAttributes) -> IClusterpublic static ICluster fromClusterAttributes(Construct scope, String id, ClusterAttributes attrs)public static ICluster FromClusterAttributes(Construct scope, string id, ClusterAttributes attrs)func FromClusterAttributes(Scope Construct, Id *string, Attrs ClusterAttributes) IClusterstatic#grantTaskProtection(grantee: IGrantable): Grantdef grant_task_protection(self, grantee: IGrantable) -> Grantpublic Grant grantTaskProtection(IGrantable grantee)public Grant GrantTaskProtection(IGrantable grantee)func GrantTaskProtection(Grantee IGrantable) Grant#This method provides a streamlined way to assign the 'ecs:UpdateTaskProtection' permission, enabling the grantee to manage task protection in the ECS cluster. [disable-awslint:no-grants]
1 parameter
Parameters
granteegranteegranteegranteeGrantee— The entity (e.g., IAM role or user) to grant the permissions to.
isCluster(x: any): boolean@staticmethod def is_cluster(x: Any) -> boolpublic static Boolean isCluster(Object x)public static bool IsCluster(object x)func IsCluster(X interface{}) *boolstatic#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#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.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#metricCpuReservation(props?: MetricOptions): Metricdef metric_cpu_reservation(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCpuReservation(MetricOptions props)public Metric MetricCpuReservation(MetricOptions? props = null)func MetricCpuReservation(Props MetricOptions) Metric#metricCpuUtilization(props?: MetricOptions): Metricdef metric_cpu_utilization(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCpuUtilization(MetricOptions props)public Metric MetricCpuUtilization(MetricOptions? props = null)func MetricCpuUtilization(Props MetricOptions) Metric#metricMemoryReservation(props?: MetricOptions): Metricdef metric_memory_reservation(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricMemoryReservation(MetricOptions props)public Metric MetricMemoryReservation(MetricOptions? props = null)func MetricMemoryReservation(Props MetricOptions) Metric#metricMemoryUtilization(props?: MetricOptions): Metricdef metric_memory_utilization(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricMemoryUtilization(MetricOptions props)public Metric MetricMemoryUtilization(MetricOptions? props = null)func MetricMemoryUtilization(Props MetricOptions) Metric#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#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.