You need to enable JavaScript to run this app. AWS CDK Python自定义构造添加方法示例求助
优惠活动
大模型
产品
解决方案
定价
更多

AWS CDK Python自定义构造添加方法示例求助

在Python AWS CDK自定义构造中添加方法的实用示例

下面直接给你几个针对L1 Cfn构造封装自定义方法的实操例子,都是个人自用场景下的典型写法:

示例1:封装S3 L1 Bucket,添加常用配置方法

这个例子把L1的CfnBucket封装成自定义构造,添加了自动归档、CORS配置、快捷获取ARN的方法:

from constructs import Construct
import aws_cdk.aws_s3 as s3

class MyCustomBucket(Construct):
    def __init__(self, scope: Construct, id: str, bucket_name: str, **kwargs):
        super().__init__(scope, id, **kwargs)
        
        # 内部封装L1的S3 Bucket,预设版本开启
        self._cfn_bucket = s3.CfnBucket(
            self,
            "Bucket",
            bucket_name=bucket_name,
            versioning_configuration=s3.CfnBucket.VersioningConfigurationProperty(
                status="Enabled"
            )
        )
    
    # 自定义方法:添加文件自动归档到Glacier的规则
    def add_glacier_transition(self, days: int, prefix: str = None):
        # 构造生命周期规则属性
        rule = s3.CfnBucket.LifecycleRuleProperty(
            status="Enabled",
            transition=s3.CfnBucket.TransitionProperty(
                storage_class="GLACIER",
                days=days
            )
        )
        if prefix:
            rule.prefix = prefix
        
        # 兼容已有规则,避免覆盖
        existing_rules = self._cfn_bucket.lifecycle_configuration or {}
        rules_list = existing_rules.get("rules", [])
        rules_list.append(rule)
        
        self._cfn_bucket.lifecycle_configuration = s3.CfnBucket.LifecycleConfigurationProperty(
            rules=rules_list
        )
    
    # 用@property简化获取Bucket ARN
    @property
    def arn(self) -> str:
        return self._cfn_bucket.attr_arn
    
    # 自定义方法:一键设置CORS规则
    def set_cors(self, allowed_origins: list[str], allowed_methods: list[str]):
        cors_rule = s3.CfnBucket.CorsRuleProperty(
            allowed_origins=allowed_origins,
            allowed_methods=allowed_methods,
            allowed_headers=["*"]
        )
        self._cfn_bucket.cors_configuration = s3.CfnBucket.CorsConfigurationProperty(
            cors_rules=[cors_rule]
        )

使用方式

在你的Stack里直接调用:

from aws_cdk import Stack
from constructs import Construct

class MyStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        
        # 创建自定义Bucket
        my_bucket = MyCustomBucket(self, "MyPersonalBucket", bucket_name="my-bucket-123xyz")
        
        # 添加30天后归档的规则,仅针对old-data前缀下的文件
        my_bucket.add_glacier_transition(days=30, prefix="old-data/")
        
        # 设置允许指定域名的GET/PUT请求
        my_bucket.set_cors(allowed_origins=["https://my-app.dev"], allowed_methods=["GET", "PUT"])
        
        # 直接获取ARN并导出
        self.export_value(my_bucket.arn)

示例2:封装EC2 L1实例,添加标签和安全组快捷配置

针对L1的CfnInstance封装,预设SSH和HTTP安全组,添加批量打标签的方法:

from constructs import Construct
import aws_cdk.aws_ec2 as ec2

class MyCustomEc2(Construct):
    def __init__(self, scope: Construct, id: str, instance_type: str, vpc: ec2.IVpc, **kwargs):
        super().__init__(scope, id, **kwargs)
        
        # 预设安全组:允许SSH和HTTP
        self._sg = ec2.CfnSecurityGroup(
            self,
            "InstanceSG",
            group_description="SSH + HTTP access",
            vpc_id=vpc.vpc_id,
            security_group_ingress=[
                ec2.CfnSecurityGroup.IngressProperty(
                    ip_protocol="tcp",
                    from_port=22,
                    to_port=22,
                    cidr_ip="0.0.0.0/0"
                ),
                ec2.CfnSecurityGroup.IngressProperty(
                    ip_protocol="tcp",
                    from_port=80,
                    to_port=80,
                    cidr_ip="0.0.0.0/0"
                )
            ]
        )
        
        # 封装L1 EC2实例
        self._cfn_instance = ec2.CfnInstance(
            self,
            "EC2Instance",
            instance_type=instance_type,
            image_id="ami-0c55b159cbfafe1f0", # 替换成你区域的Amazon Linux 2 AMI
            security_group_ids=[self._sg.attr_group_id],
            subnet_id=vpc.public_subnets[0].subnet_id
        )
    
    # 自定义方法:批量添加标签
    def add_tags(self, tag_dict: dict[str, str]):
        existing_tags = self._cfn_instance.tags or []
        for key, val in tag_dict.items():
            existing_tags.append(ec2.CfnInstance.TagProperty(key=key, value=val))
        self._cfn_instance.tags = existing_tags
    
    # 快捷获取实例ID
    @property
    def instance_id(self) -> str:
        return self._cfn_instance.attr_id

使用方式

class MyEc2Stack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        
        # 创建或传入已有的VPC
        vpc = ec2.Vpc(self, "MyDevVpc", max_azs=2)
        
        # 创建自定义EC2实例
        dev_instance = MyCustomEc2(
            self,
            "DevEc2",
            instance_type="t2.micro",
            vpc=vpc
        )
        
        # 批量打标签
        dev_instance.add_tags({"Env": "Dev", "Name": "MyDevServer", "Project": "PersonalDemo"})

核心思路总结

  1. 自定义构造继承constructs.Construct,内部封装L1的Cfn对象(用私有属性如_cfn_bucket隐藏,避免外部直接修改)
  2. 把你平时重复写的L1配置逻辑,封装成类的方法,比如添加规则、设置权限、批量操作等
  3. 用@property装饰器封装常用属性的获取,简化调用
  4. 方法里注意兼容已有配置(比如示例中处理生命周期规则时不覆盖原有规则)

内容的提问来源于stack exchange,提问作者Tom B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:20:52