Skip to content

Commit

Permalink
fix(ecs): stack name check for capacity provider name compliance
Browse files Browse the repository at this point in the history
  • Loading branch information
msambol committed Feb 23, 2024
1 parent 7a4c189 commit 854ca8d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/aws-cdk-lib/aws-ecs/lib/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
24 changes: 24 additions & 0 deletions packages/aws-cdk-lib/aws-ecs/test/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 854ca8d

Please sign in to comment.