Skip to content
v2.274.0

ManagedInstancesCapacityProvider ​

A Managed Instances Capacity Provider.

This allows an ECS cluster to use Managed Instances for task placement with managed infrastructure.

Example ​

ts
declare const vpc: ec2.Vpc;

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

const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
  vpc,
  description: 'Security group for managed instances',
});

const miCapacityProvider = new ecs.ManagedInstancesCapacityProvider(this, 'MICapacityProvider', {
  capacityOptionType: ecs.CapacityOptionType.SPOT,
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  instanceRequirements: {
    vCpuCountMin: 1,
    memoryMin: Size.gibibytes(2),
  },
});

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.connections.allowFrom(ec2.Peer.ipv4(vpc.vpcCidrBlock), ec2.Port.tcp(80));

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProvider);

const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
  memoryMiB: '512',
  cpu: '256',
  networkMode: ecs.NetworkMode.AWS_VPC,
  compatibility: ecs.Compatibility.MANAGED_INSTANCES,
});

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  memoryReservationMiB: 256,
});

new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: miCapacityProvider.capacityProviderName,
      weight: 1,
    },
  ],
});
python
# vpc: ec2.Vpc


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

security_group = ec2.SecurityGroup(self, "SecurityGroup",
    vpc=vpc,
    description="Security group for managed instances"
)

mi_capacity_provider = ecs.ManagedInstancesCapacityProvider(self, "MICapacityProvider",
    capacity_option_type=ecs.CapacityOptionType.SPOT,
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    instance_requirements=ec2.InstanceRequirementsConfig(
        v_cpu_count_min=1,
        memory_min=Size.gibibytes(2)
    )
)

# Optionally configure security group rules using IConnectable interface
mi_capacity_provider.connections.allow_from(ec2.Peer.ipv4(vpc.vpc_cidr_block), ec2.Port.tcp(80))

# Add the capacity provider to the cluster
cluster.add_managed_instances_capacity_provider(mi_capacity_provider)

task_definition = ecs.TaskDefinition(self, "TaskDef",
    memory_mi_b="512",
    cpu="256",
    network_mode=ecs.NetworkMode.AWS_VPC,
    compatibility=ecs.Compatibility.MANAGED_INSTANCES
)

task_definition.add_container("web",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b=256
)

ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider=mi_capacity_provider.capacity_provider_name,
        weight=1
    )
    ]
)
java
Vpc vpc;


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

SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
        .vpc(vpc)
        .description("Security group for managed instances")
        .build();

ManagedInstancesCapacityProvider miCapacityProvider = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProvider")
        .capacityOptionType(CapacityOptionType.SPOT)
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .instanceRequirements(InstanceRequirementsConfig.builder()
                .vCpuCountMin(1)
                .memoryMin(Size.gibibytes(2))
                .build())
        .build();

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.connections.allowFrom(Peer.ipv4(vpc.getVpcCidrBlock()), Port.tcp(80));

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProvider);

TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
        .memoryMiB("512")
        .cpu("256")
        .networkMode(NetworkMode.AWS_VPC)
        .compatibility(Compatibility.MANAGED_INSTANCES)
        .build();

taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryReservationMiB(256)
        .build());

FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(miCapacityProvider.getCapacityProviderName())
                .weight(1)
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;


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

var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps {
    Vpc = vpc,
    Description = "Security group for managed instances"
});

var miCapacityProvider = new ManagedInstancesCapacityProvider(this, "MICapacityProvider", new ManagedInstancesCapacityProviderProps {
    CapacityOptionType = CapacityOptionType.SPOT,
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    InstanceRequirements = new InstanceRequirementsConfig {
        VCpuCountMin = 1,
        MemoryMin = Size.Gibibytes(2)
    }
});

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.Connections.AllowFrom(Peer.Ipv4(vpc.VpcCidrBlock), Port.Tcp(80));

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProvider);

var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
    MemoryMiB = "512",
    Cpu = "256",
    NetworkMode = NetworkMode.AWS_VPC,
    Compatibility = Compatibility.MANAGED_INSTANCES
});

taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryReservationMiB = 256
});

new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = miCapacityProvider.CapacityProviderName,
        Weight = 1
    } }
});
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,
})

securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
	Description: jsii.String("Security group for managed instances"),
})

miCapacityProvider := ecs.NewManagedInstancesCapacityProvider(this, jsii.String("MICapacityProvider"), &ManagedInstancesCapacityProviderProps{
	CapacityOptionType: ecs.CapacityOptionType_SPOT,
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	InstanceRequirements: &InstanceRequirementsConfig{
		VCpuCountMin: jsii.Number(1),
		MemoryMin: awscdk.Size_Gibibytes(jsii.Number(2)),
	},
})

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.Connections.AllowFrom(ec2.Peer_Ipv4(vpc.VpcCidrBlock), ec2.Port_Tcp(jsii.Number(80)))

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProvider)

taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDef"), &TaskDefinitionProps{
	MemoryMiB: jsii.String("512"),
	Cpu: jsii.String("256"),
	NetworkMode: ecs.NetworkMode_AWS_VPC,
	Compatibility: ecs.Compatibility_MANAGED_INSTANCES,
})

taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryReservationMiB: jsii.Number(256),
})

ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: miCapacityProvider.CapacityProviderName,
			Weight: jsii.Number(1),
		},
	},
})

Initializer ​

ts
new ManagedInstancesCapacityProvider(scope: Construct, id: string, props: ManagedInstancesCapacityProviderProps)
python
ManagedInstancesCapacityProvider(scope: Construct, id: str, props: ManagedInstancesCapacityProviderProps)
java
new ManagedInstancesCapacityProvider(Construct scope, String id, ManagedInstancesCapacityProviderProps props)
csharp
new ManagedInstancesCapacityProvider(Construct scope, string id, ManagedInstancesCapacityProviderProps props)
go
NewManagedInstancesCapacityProvider(Scope Construct, Id *string, Props ManagedInstancesCapacityProviderProps)

Construct Props ​

capacityOptionTypeCapacityOptionTypecapacity_option_typeCapacityOptionTypecapacityOptionTypeCapacityOptionTypeCapacityOptionTypeCapacityOptionTypeCapacityOptionTypeCapacityOptionType= `ON_DEMAND`#
Specifies the capacity option type for instances launched by this capacity provider.

This determines whether instances are launched as On-Demand or Spot instances.

capacityProviderNamestringcapacity_provider_namestrcapacityProviderNameStringCapacityProviderNamestringCapacityProviderName*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-.

ec2InstanceProfileIInstanceProfileec2_instance_profileIInstanceProfileec2InstanceProfileIInstanceProfileEc2InstanceProfileIInstanceProfileEc2InstanceProfileIInstanceProfile#
The EC2 instance profile that will be attached to instances launched by this capacity provider.

Default: A new instance profile prefixed with 'ecsInstanceRole' will be created

notes

This instance profile must contain the necessary IAM permissions for ECS container instances to register with the cluster and run tasks. At minimum, it should include permissions for ECS agent communication, ECR image pulling, and CloudWatch logging.

If you are using Amazon ECS Managed Instances with the AWS-managed Infrastructure policy (AmazonECSInfrastructureRolePolicyForManagedInstances), the instance profile must be prefixed with ecsInstanceRole for the built in PassRole policy to apply.

If you are using a custom policy for the Infrastructure role, the instance profile can have an alternative name.

infrastructureRoleIRoleinfrastructure_roleIRoleinfrastructureRoleIRoleInfrastructureRoleIRoleInfrastructureRoleIRole#
The IAM role that ECS uses to manage the infrastructure for the capacity provider.

Default: A new role will be created with the AmazonECSInfrastructureRolePolicyForManagedInstances managed policy

This role is used by ECS to perform actions such as launching and terminating instances, managing Auto Scaling Groups, and other infrastructure operations required for the managed instances capacity provider.

instanceRequirementsInstanceRequirementsConfiginstance_requirementsInstanceRequirementsConfiginstanceRequirementsInstanceRequirementsConfigInstanceRequirementsInstanceRequirementsConfigInstanceRequirementsInstanceRequirementsConfig#
The instance requirements configuration for EC2 instance selection.

Default: no specific instance requirements, ECS will choose appropriate instances

notes

This allows you to specify detailed requirements for instance selection including vCPU count ranges, memory ranges, CPU manufacturers (Intel, AMD, AWS Graviton), instance generations, network performance requirements, and many other criteria. ECS will automatically select appropriate instance types that meet these requirements.

The CloudWatch monitoring configuration for the EC2 instances.

Default: no enhanced monitoring (basic monitoring only)

Determines the granularity of CloudWatch metrics collection for the instances. Detailed monitoring incurs additional costs but provides better observability.

Specifies whether to propagate tags from the capacity provider to the launched instances.

Default: PropagateManagedInstancesTags.NONE - no tag propagation

When set to CAPACITY_PROVIDER, tags applied to the capacity provider resource will be automatically applied to all EC2 instances launched by this capacity provider.

securityGroupsISecurityGroup[]security_groupstyping.List[ISecurityGroup]securityGroupsList<ISecurityGroup>SecurityGroupsISecurityGroup[]SecurityGroups*[]ISecurityGrouprequired#
The security groups to associate with the launched EC2 instances.

These security groups control the network traffic allowed to and from the instances.

subnetsISubnet[]subnetstyping.List[ISubnet]subnetsList<ISubnet>SubnetsISubnet[]Subnets*[]ISubnetrequired#
The VPC subnets where EC2 instances will be launched.

This array must be non-empty and should contain subnets from the VPC where you want the managed instances to be deployed.

taskVolumeStorageSizetask_volume_storageSizetaskVolumeStorageSizeTaskVolumeStorageSizeTaskVolumeStorageSize= Size.gibibytes(80)#
The size of the task volume storage attached to each instance.

This storage is used for container images, container logs, and temporary files. Larger storage may be needed for workloads with large container images or applications that generate significant temporary data.

Properties ​

capacityProviderNamestringcapacity_provider_namestrcapacityProviderNameStringCapacityProviderNamestringCapacityProviderName*stringrequired#
Capacity provider name.
clusterIClusterclusterIClusterclusterIClusterClusterIClusterClusterICluster#
The cluster this capacity provider is associated with.
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
The network connections associated with this resource.
ec2InstanceProfileIInstanceProfileec2_instance_profileIInstanceProfileec2InstanceProfileIInstanceProfileEc2InstanceProfileIInstanceProfileEc2InstanceProfileIInstanceProfilerequired#
The EC2 instance profile attached to instances launched by this capacity provider.
infrastructureRoleIRoleinfrastructure_roleIRoleinfrastructureRoleIRoleInfrastructureRoleIRoleInfrastructureRoleIRolerequired#
The IAM role that ECS uses to manage the infrastructure for the capacity provider.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.

Methods ​

bind(cluster: ICluster): voiddef bind(self, cluster: ICluster) -> Nonepublic void bind(ICluster cluster)public void Bind(ICluster cluster)func Bind(Cluster ICluster)#
Associates the capacity provider with the specified cluster.

This method is called by the cluster when adding the capacity provider.

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