Cyclic SecurityGroup problem when sharing ALB between stacks
-
I'm submitting a ...
- [x] :beetle: bug report
- [ ] :rocket: feature request
- [ ] :books: construct library gap
- [ ] :phone: security issue or vulnerability => Please see policy
- [ ] :question: support request => Please see note at the top of this template.
-
What is the current behavior?
- Construct an ALB in Stack A with a default listener and expose it to other stacks
- Create a new Stack B and in that stack add a listener rule to the default listener from Stack A
Doing this will create a cyclic reference:
Error: 'stackA' depends on 'stackB' (stackA/TaskExecutionRole/DefaultPolicy/Resource -> stackB/MysqlECR/Resource.Arn).
Adding this dependency (stackB/PublicLoadBalancer/SecurityGroup/to stackBServiceSecurityGroupC0940D52:80 -> stackA/Service/SecurityGroup/Resource.GroupId) would create a cyclic reference.
at AppInfraStack.addDependency (cdk_project/cdk/node_modules/@aws-cdk/core/lib/stack.ts:273:15)
at CfnReference.consumeFromStack (cdk_project/cdk/node_modules/@aws-cdk/core/lib/private/cfn-reference.ts:131:22)
at AppInfraStack.prepare (cdk_project/cdk/node_modules/@aws-cdk/core/lib/stack.ts:490:23)
at Function.prepare (cdk_project/cdk/node_modules/@aws-cdk/core/lib/construct.ts:84:28)
at Function.synth (cdk_project/cdk/node_modules/@aws-cdk/core/lib/construct.ts:41:10)
at App.synth (cdk_project/cdk/node_modules/@aws-cdk/core/lib/app.ts:128:36)
at process.<anonymous> (cdk_project/cdk/node_modules/@aws-cdk/core/lib/app.ts:111:45)
at Object.onceWrapper (events.js:288:20)
at process.emit (events.js:200:13)
at process.EventEmitter.emit (domain.js:471:20)
StackA:
export class StackA extends cdk.Stack {
public readonly alb: SharedALB;
public readonly cluster: ecs.Cluster;
public readonly vpc: IVpc;
...
this.alb = new SharedALB(this, 'PublicLoadBalancer', {
vpc,
certificateArns,
internetFacing: true,
});
...
StackB:
export class StackB extends cdk.Stack {
...
const service = new ecs.FargateService(this, 'Service', {
taskDefinition: task,
cluster: props.stackA.cluster,
vpcSubnets: {subnetType: SubnetType.PRIVATE},
});
const targetGroup = new elbv2.ApplicationTargetGroup(this, 'TargetGroup', {
healthCheck: {
path: '/',
protocol: elbv2.Protocol.HTTP,
interval: Duration.seconds(30),
timeout: Duration.seconds(10),
healthyThresholdCount: 2,
unhealthyThresholdCount: 10,
port: '80',
},
targetType: TargetType.IP,
port: 80,
protocol: ApplicationProtocol.HTTP,
vpc: props.stackA.vpc,
targets: [service],
});
props.stackA.alb.defaultListener.addTargetGroups('ECSServiceRule', {
targetGroups: [targetGroup],
pathPattern: '*',
priority: 1,
});
...
Where the exposed props.stackA.alb is a custom resource that looks like:
export class SharedALB extends elbv2.ApplicationLoadBalancer {
readonly defaultListener: ApplicationListener;
constructor(scope: cdk.Construct, id: string, props: SharedALBProps) {
super(scope, id, props);
this.defaultListener = this.addListener('Listener', {
port: 443,
certificateArns: props.certificateArns,
open: true,
sslPolicy: elbv2.SslPolicy.RECOMMENDED,
});
this.defaultListener.addFixedResponse('Default404', {
statusCode: '404'
});
new cdk.CfnOutput(scope, 'PublicLoadBalancerDNSName', {
description: 'The DNS name of the load balancer',
value: this.loadBalancerDnsName,
});
}
}
- What is the expected behavior (or behavior of feature suggested)?
Expect it to synth a
AWS::ElasticLoadBalancingV2::ListenerRulein Stack B similar to what this construct would do:
new CfnListenerRule(this, 'ECSServiceRule', {
actions: [
{
targetGroupArn: targetGroup.targetGroupArn,
type: 'forward'
}
],
conditions: [
{
field: 'path-pattern',
values: ['*']
},
],
listenerArn: props.stackA.alb.defaultListener.listenerArn,
priority: 1,
});
-
Please tell us about your environment:
- CDK CLI Version: 1.4.0 (build 175471f)
- Module Version: 1.4.0
- OS: OSX Mojave
- Language: TypeScript
-
Other information
This is somewhat similar to the use case in #1957. The difference in the approach here is that the ALB is constructed within the same application, not imported, so I believe CDK is choking on trying to resolve dependency graph between the two stack objects.
This is also very similar to the problem defined in #1654, except in this case I can't seem to resolve using the same solution. I've tried several things such as explicitly creating a securityGroup for the service in stackB, then doing:
securityGroup.connections.allowTo(props.stackA.alb.defaultListener, Port.tcp(80));
securityGroup.connections.allowFrom(props.stackA.alb.defaultListener, Port.tcp(80));
from within stackB. Have also tried:
service.connections.allowFrom(props.stackA.alb, Port.tcp(80));
service.connections.allowToAnyIpv4(Port.allTcp());
Have also tried different ways to add the rule instead of using props.stackA.alb.defaultListener.addTargetGroups, such as:
new ApplicationListenerRule(this, 'ECSServiceRule', {
targetGroups: [targetGroup],
pathPattern: '*',
listener: props.stackA.alb.defaultListener,
priority: 1,
});
The only thing that has worked so far is to directly use CfnListenerRule, or just create the ALB in stackB, which I'd like to avoid both.
Created a basic application to reproduce it https://github.com/jgondron/aws_cdk_3689. This obviously won't deploy, but it can be used to reproduce the issue with cdk synth
I just ran into this as well and started poking around inside CDK. While researching behavior I came across this:
When each task starts, the IP address of its elastic network interface is added to the load balancer’s configuration.
https://aws.amazon.com/blogs/compute/task-networking-in-aws-fargate/
I believe the issue is with this line:
https://github.com/aws/aws-cdk/blob/364aa8deca377ece97e1367dd5ba6c2b21526e94/packages/%40aws-cdk/aws-ecs/lib/base/base-service.ts#L223-L233
CDK is assuming that a port needs to be registered when in fact, Fargate should do it behind the scenes, so long as it is attached to the ALB. In my local fork, I am testing what happens if I override that method in FargateService and only call attachToELBv2
@parisholley @rix0rrr Just confirmed that this is fixed in v1.9.0. Thanks for such a quick resolution!
Something to note: the fix in #4111 does allow me to add a rule via the elbv2. ApplicationListenerRule method, but my previous approach of adding target groups to the listener still exhibits the problem, ex:
parentStack.listener.addTargetGroups('ListenerRule', {
targetGroups: [childGroup],
priority: 1,
pathPattern: '*',
});
I'm fine with using the fixed approach, but I'm not sure you guys will want to close this issue if it will still crop up in the other code paths.
I updated my project to show the remaining issue https://github.com/jgondron/aws_cdk_3689/blob/master/lib/stackB.ts#L68.
@jgondron curious, what is your use case for adding a target group to an existing listener? I have different paths going to different applications (stacks), so this fix supports the intended use case of an ALB with dynamic routing.
by modifying an existing target group, I feel the behavior you are hitting is to be expected? if the target groups are completely unrelated and require different stacks, you should probably be using a different construct (eg: network load balancer).
Forgive me, perhaps I'm using this method in a way that was unintended, but isn't this supposed to do the same thing as directly calling elbv2.ApplicationListenerRule, except with a slightly different abstraction? From what I originally understood using this, it would add a new listener rule to an existing listener, with the rule pointing to the target group provided. Which should be similar to the other method, except your abstractly interacting with ALB and targets instead of the rules themselves.
@jgondron i see what your saying. while yes, conceptually you are doing the same thing, within the CDK you are not. calling listener.addTargetGroups() is going to scope everything it creates (eg: the rule with the targeting group), to the stack in which the listener is scoped (in your case, the parent). you HAVE to create a rule that is scoped to the child stack, and the only way to do that, is manually.
Oh yes, this is the problem I thought wouldn't occur in practice (if you're thinking about services and LBs), but it does occur if you're thinking about individual target groups.
So there are two situations to distinguish:
- Load balancer/listener exists in a shared stack, we're creating a Target Group in a downstream stack (listener rule needs to be created in the Target Group stack).
- Target group exists in a shared stack, we're creating a listener and we want to route to the existing stack (listener rule needs to be created in the listener stack).
Right now, there is only one API call and it obviously cannot cover both scenario's -- I don't want to get into automatic detection of other dependency arrows, that way lies madness when the ordering inevitably doesn't work out quite correctly.
The only solution is to have a second API which does the same as the first, but puts the listener rule in a different scope, (like peer1.connections.allowFrom(peer2) and peer2.connections.allowTo(peer1), which do the same thing ultimately but differ in scope of where they put the ingress and egress rules.
Another solution is to have an additional argument which controls the scope of the rule object.
I am open to suggestions!
If I had to choose one of those, I'd say just allow providing the scope. My guess is that most users who are just learning cdk will just use this by default for any methods that require scope, and when inside of the stack that's instantiating the object this is probably what you want as a reasonable default.
as far as I am aware, is it isn't a pattern used anywhere else in the CDK (passing scope at function level), expected behavior is all of those methods always bind to the scope of the called function and passing references from another stack, inherently will cause a dependency. while it is annoying, it is consistent :) i prefer to not have to keep up with which parts of the API are smart, and which aren't.
also as a note, the fact that this pull fixed cross-stack issues is really a by-product, the real underlying issue was that direction in which security groups were applied.
i would advocate that if you want a new rule created and it points to TGs in your child stack, the rule should be created in your child stack, and added to the parent listener vs. relying on a "nested" utility function to handle edge cases
Sure, that's fair enough. Just to reiterate, I'm perfectly fine with creating the rule directly. I was more looking to future users that might hit this problem. But, I definitely don't want to argue a use case that doesn't actually exist for me, so maybe it makes more sense to just close this out and see if any other problems arise?
Okay, I will close this out for now, and wait for a reopen.