diff --git a/packages/aws-cdk-lib/aws-ecs/lib/cluster.ts b/packages/aws-cdk-lib/aws-ecs/lib/cluster.ts index e65e62d4b2813..5e56c39720856 100644 --- a/packages/aws-cdk-lib/aws-ecs/lib/cluster.ts +++ b/packages/aws-cdk-lib/aws-ecs/lib/cluster.ts @@ -1300,10 +1300,15 @@ export class AsgCapacityProvider extends Construct { this.autoScalingGroup.protectNewInstancesFromScaleIn(); } + const capacityProviderNameRegex = /^(?!aws|ecs|fargate).+/gm; if (props.capacityProviderName) { - if (!(/^(?!aws|ecs|fargate).+/gm.test(props.capacityProviderName))) { + if (!(capacityProviderNameRegex.test(props.capacityProviderName))) { throw new Error(`Invalid Capacity Provider Name: ${props.capacityProviderName}, If a name is specified, it cannot start with aws, ecs, or fargate.`); } + } else { + if (!(capacityProviderNameRegex.test(Stack.of(this).stackName))) { + throw new Error(`Invalid Capacity Provider Name: ${Stack.of(this).stackName}, No name was specified, the stack name cannot start with aws, ecs, or fargate.`); + } } if (props.instanceWarmupPeriod && !Token.isUnresolved(props.instanceWarmupPeriod)) { diff --git a/packages/aws-cdk-lib/aws-ecs/test/cluster.test.ts b/packages/aws-cdk-lib/aws-ecs/test/cluster.test.ts index 3ba6f23a71c3c..e7970243721ba 100644 --- a/packages/aws-cdk-lib/aws-ecs/test/cluster.test.ts +++ b/packages/aws-cdk-lib/aws-ecs/test/cluster.test.ts @@ -2945,6 +2945,30 @@ test('throws when ASG Capacity Provider with capacityProviderName starting with }).toThrow(/Invalid Capacity Provider Name: ecscp, If a name is specified, it cannot start with aws, ecs, or fargate./); }); +test('throws when ASG Capacity Provider with no capacityProviderName but stack name starting with aws, ecs or faragte', () => { + // GIVEN + const app = new cdk.App(); + const stack = new cdk.Stack(app, 'ecscp'); + const vpc = new ec2.Vpc(stack, 'Vpc'); + const cluster = new ecs.Cluster(stack, 'EcsCluster'); + + const autoScalingGroupAl2 = new autoscaling.AutoScalingGroup(stack, 'asgal2', { + vpc, + instanceType: new ec2.InstanceType('bogus'), + machineImage: ecs.EcsOptimizedImage.amazonLinux2(), + }); + + expect(() => { + // WHEN Capacity Provider when stack name starts with ecs. + const capacityProviderAl2 = new ecs.AsgCapacityProvider(stack, 'provideral2-2', { + autoScalingGroup: autoScalingGroupAl2, + enableManagedTerminationProtection: false, + }); + + cluster.addAsgCapacityProvider(capacityProviderAl2); + }).toThrow(/Invalid Capacity Provider Name: ecscp, No name was specified, the stack name cannot start with aws, ecs, or fargate./); +}); + test('throws when InstanceWarmupPeriod is less than 0', () => { // GIVEN const app = new cdk.App();