CDK Python最新版中ApplicationLoadBalancer.add_security_group方法报错求助
It’s not a bug—this is just a common point of confusion with how AWS CDK handles security groups for Application Load Balancers! The ApplicationLoadBalancer object itself doesn’t have an add_security_group method, but its underlying connections property does. Here’s how to fix your code:
Correct Approach
Instead of calling add_security_group directly on the ALB instance, access the connections attribute first:
something = elbv2.ApplicationLoadBalancer(...) something.connections.add_security_group(securitygroupid)
Why This Works
In AWS CDK, most network-aware constructs (including ALBs) implement the IConnectable interface, which exposes a connections property. This property is where you manage security group associations, inbound/outbound rules, and other network access controls. The add_security_group method lives here, not on the ALB object itself.
Alternative: Specify Security Groups During Construction
If you know the security groups you want to associate upfront, you can pass them directly when creating the ALB using the security_groups parameter in the constructor:
something = elbv2.ApplicationLoadBalancer( self, "MyALB", # other required properties like vpc, internet_facing, etc. security_groups=[securitygroupid] )
If you encountered documentation that mentioned add_security_group for ALBs, it’s likely referring to the method nested under connections—sometimes docs shorthand this detail, leading to the mix-up.
内容的提问来源于stack exchange,提问作者Frank Mancini

