如何在AWS CDK v2中将自定义值传递给Lambda自定义资源
向AWS CDK自定义资源Lambda传递自定义参数的实现方法
方法一:通过CustomResource的Properties传递动态参数
这是传递自定义资源专属动态参数的最优方式,参数会随自定义资源的创建/更新事件同步传递给Lambda。
修改栈配置代码
在CustomResource定义中添加properties字段,填入需要传递的自定义值(包括账号ID、区域这类CDK内置变量):
from constructs import Construct from aws_cdk import ( Stack, custom_resources as cr, aws_lambda as _lambda, CustomResource ) class MyStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) cust_res_lambda = _lambda.Function( self, 'crLambda', runtime=_lambda.Runtime.PYTHON_3_8, code=_lambda.Code.from_asset('my-resources'), handler='lambda.lambda_handler', function_name='cr_Lambda' ) res_provider = cr.Provider( self,'crProvider', on_event_handler= cust_res_lambda ) # 新增properties传递自定义参数 CustomResource(self, 'cust_res', service_token= res_provider.service_token, properties={ "custom_string": "我的专属自定义字符串", "aws_account_id": self.account, "aws_region": self.region, "custom_json": { "config_key": "config_value", "list_data": ["item1", "item2"] } } )
修改Lambda代码获取参数
在Lambda的event对象中,自定义参数会被封装在ResourceProperties字段里,直接读取即可:
import json def lambda_handler(event, context): print('lambda executed') # 提取自定义参数 resource_props = event.get('ResourceProperties', {}) custom_str = resource_props.get('custom_string') account_id = resource_props.get('aws_account_id') region = resource_props.get('aws_region') custom_json = resource_props.get('custom_json') # 打印验证参数 print(f"自定义字符串: {custom_str}") print(f"AWS账号ID: {account_id}") print(f"AWS区域: {region}") print(f"自定义JSON: {json.dumps(custom_json)}") # 处理自定义资源的不同事件类型(可选) event_type = event.get('RequestType') if event_type == 'Create': print("执行资源创建逻辑") elif event_type == 'Update': print("执行资源更新逻辑") elif event_type == 'Delete': print("执行资源删除逻辑") # 必须返回符合自定义资源规范的响应 return { 'PhysicalResourceId': 'my-custom-resource-id', 'Data': { 'Result': '参数接收成功' } }
方法二:通过Lambda环境变量传递静态参数
适合传递全局固定的配置(如账号ID、区域、通用常量),参数会在Lambda部署时注入,无需随自定义资源事件传递。
修改栈配置代码
在Lambda函数定义中添加environment字段:
cust_res_lambda = _lambda.Function( self, 'crLambda', runtime=_lambda.Runtime.PYTHON_3_8, code=_lambda.Code.from_asset('my-resources'), handler='lambda.lambda_handler', function_name='cr_Lambda', # 新增环境变量 environment={ "AWS_ACCOUNT_ID": self.account, "AWS_REGION": self.region, "FIXED_CONFIG": "全局固定配置值" } )
修改Lambda代码获取参数
通过os.environ读取环境变量:
import os def lambda_handler(event, context): print('lambda executed') # 读取环境变量 account_id = os.environ.get('AWS_ACCOUNT_ID') region = os.environ.get('AWS_REGION') fixed_config = os.environ.get('FIXED_CONFIG') print(f"账号ID: {account_id}") print(f"区域: {region}") print(f"固定配置: {fixed_config}") # 其他业务逻辑... return { 'PhysicalResourceId': 'my-custom-resource-id', 'Data': { 'Result': '环境变量读取成功' } }
内容的提问来源于stack exchange,提问作者user20358
相关产品推荐
相关产品推荐

