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

使用AWS CDK2 Python在已有VPC创建EC2安全组报错求助

解决AWS CDK2 Python中CfnSecurityGroup的序列化错误

错误原因

直接使用普通Python字典定义security_group_ingress和security_group_egress规则,而CDK的CloudFormation原生(Cfn)类要求这些属性必须是对应的Property类实例,jsii无法将普通字典序列化为CDK期望的类型,因此抛出序列化错误。


方案1:使用CfnSecurityGroup的Property类构建规则

修改规则定义部分,用ec2.CfnSecurityGroup.IngressProperty和ec2.CfnSecurityGroup.EgressProperty创建规则对象,替换原有的普通字典:

import aws_cdk as cdk
from aws_cdk import aws_ec2 as ec2

class YourStack(cdk.Stack):
    def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        
        ec2securitygroup = ec2.CfnSecurityGroup(
            self,
            "EC2SecurityGroup2",
            group_description="Security group for ec2",
            group_name="test-security-group",
            tags=[
                {
                    "key": "Name",
                    "value": "test-security-group"
                }
            ],
            vpc_id="vpc-1234567",
            security_group_ingress=[
                ec2.CfnSecurityGroup.IngressProperty(
                    cidr_ip="10.0.0.0/16",
                    description="Allow all internal traffic from VPC1",
                    ip_protocol="-1"
                ),
                ec2.CfnSecurityGroup.IngressProperty(
                    source_security_group_id="sg-123456789",
                    source_security_group_owner_id="123456789",
                    from_port=80,
                    ip_protocol="tcp",
                    to_port=80
                )
            ],
            security_group_egress=[
                ec2.CfnSecurityGroup.EgressProperty(
                    cidr_ip="0.0.0.0/0",
                    description="Allow outbound traffic",
                    ip_protocol="-1"
                )
            ]
        )

方案2:使用CDK高阶SecurityGroup类(推荐)

CDK提供了更易用的ec2.SecurityGroup高阶类,它会自动处理底层CloudFormation属性的序列化,代码更简洁且符合CDK最佳实践:

import aws_cdk as cdk
from aws_cdk import aws_ec2 as ec2
from aws_cdk import Tags

class YourStack(cdk.Stack):
    def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        
        # 导入已有VPC
        existing_vpc = ec2.Vpc.from_lookup(self, "ExistingVpc", vpc_id="vpc-1234567")
        
        # 创建安全组
        ec2securitygroup = ec2.SecurityGroup(
            self,
            "EC2SecurityGroup2",
            security_group_name="test-security-group",
            description="Security group for ec2",
            vpc=existing_vpc,
            allow_all_outbound=True  # 自动添加0.0.0.0/0的出站规则
        )

        # 添加入站规则
        ec2securitygroup.add_ingress_rule(
            peer=ec2.Peer.ipv4("10.0.0.0/16"),
            connection=ec2.Port.all_traffic(),
            description="Allow all internal traffic from VPC1"
        )

        ec2securitygroup.add_ingress_rule(
            peer=ec2.Peer.security_group_id("sg-123456789", owner_id="123456789"),
            connection=ec2.Port.tcp(80),
            description="Allow HTTP from specified security group"
        )

        # 添加Name标签
        Tags.of(ec2securitygroup).add("Name", "test-security-group")

高阶类的优势:提供直观的API,自动处理规则依赖关系,支持类型检查,减少手动构建Cfn属性的错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:50:27