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

Python CDK合成AWS网关负载均衡器失败问题求助

Python CDK创建网关负载均衡器(GWLB)时Sequence类型校验失败问题

我正尝试使用Python CDK创建AWS网关负载均衡器(GWLB)配置,目前已有可用的CloudFormation版本,但合成(synth)步骤失败,原因是CDK未将Python列表识别为Sequence类型。由于暂无GWLB的L2构造,我使用了L1构造编写核心代码:

gwlb = elbv2.CfnLoadBalancer(
    self,
    "GatewayLoadBalancer",
    name=f"GWLB-{self.stack_name}",
    type="gateway",
    subnets=gwlb_subnet_ids,
    scheme="internal",
    load_balancer_attributes=[
        elbv2.CfnLoadBalancer.LoadBalancerAttributeProperty(
            key="load_balancing.cross_zone.enabled", value="true"
        )
    ],
)

gw_endpoint_service = ec2.CfnVPCEndpointService(
    self,
    "VPCEndpointService",
    acceptance_required=False,
    gateway_load_balancer_arns=[gwlb.get_att("Arn")],
)

运行synth时出现如下错误:

File "/Users/pmryan/.pyenv/versions/3.8.12/lib/python3.8/site-packages/typeguard/__init__.py", line 757, in check_type
    checker_func(argname, value, expected_type, memo)
File "/Users/pmryan/.pyenv/versions/3.8.12/lib/python3.8/site-packages/typeguard/__init__.py", line 558, in check_union
    raise TypeError('type of {} must be one of ({}); got {} instead'.
TypeError: type of argument gateway_load_balancer_arns must be one of (Sequence[str], NoneType); got list instead

我疑惑这是否属于CDK Bug,因为在其他CDK构造中,我可正常将Python列表传入期望Sequence类型的参数。


问题原因与解决方案

这并不是CDK Bug,问题出在gwlb.get_att("Arn")返回的是**Reference对象**(CloudFormation引用),而非原生字符串类型。TypeGuard校验时会检查列表元素是否为字符串,Reference不满足str类型要求,因此抛出错误。

解决方法1:使用L1构造的属性访问器

对于CfnLoadBalancer,CDK提供了预定义的属性访问器attr_arn,它会正确返回字符串类型的ARN引用:

gw_endpoint_service = ec2.CfnVPCEndpointService(
    self,
    "VPCEndpointService",
    acceptance_required=False,
    gateway_load_balancer_arns=[gwlb.attr_arn],
)

解决方法2:显式转换为字符串类型

如果必须使用get_att,可以通过str()显式转换返回的Reference对象:

gw_endpoint_service = ec2.CfnVPCEndpointService(
    self,
    "VPCEndpointService",
    acceptance_required=False,
    gateway_load_balancer_arns=[str(gwlb.get_att("Arn"))],
)

解决方法3:使用类型转换绕过校验(不推荐)

可以使用typing.cast告诉TypeGuard该值符合预期类型,但这是绕过校验的方式,仅在其他方法无效时使用:

from typing import cast, Sequence

gw_endpoint_service = ec2.CfnVPCEndpointService(
    self,
    "VPCEndpointService",
    acceptance_required=False,
    gateway_load_balancer_arns=cast(Sequence[str], [gwlb.get_att("Arn")]),
)

内容的提问来源于stack exchange,提问作者Pat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:35:48