You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CDK Python最新版中ApplicationLoadBalancer.add_security_group方法报错求助

Fixing the 'add_security_group' AttributeError for ApplicationLoadBalancer in CDK Python

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:02:54