如何获取CDK Lambda backed Custom Resource的返回数据、逻辑ID与物理ID
解决方案
1. 获取Lambda返回的自定义数据与Physical Resource ID
你不需要提前获取Logical ID就能拿返回值,cdk.CustomResource 本身已经封装了对应方法:
- 获取Physical Resource ID:直接调用实例的
ref属性即可,该属性会直接返回自定义资源的物理ID - 获取Lambda返回
Data字段中的自定义属性:调用get_att(属性名)方法即可
示例代码:
# 你的Lambda返回结构示例(用于参考) def on_event(event, context): # 资源创建逻辑省略 return { "PhysicalResourceId": "Z0123456789ABCDEFG", # 你返回的物理ID "Data": { "HostedZoneId": "Z0123456789ABCDEFG", "NameServers": ["ns1.example.com", "ns2.example.com"] } }
栈中调用代码:
test = custom_hosted_zone.hz_with_delegation( self, id="some Id", delSet="N06079012Q8954F8DG91Y", env=environment) # 直接获取物理ID hz_physical_id = test.cr.ref # 获取Data中的自定义字段 hz_id = test.cr.get_att("HostedZoneId").to_string() name_servers = test.cr.get_att("NameServers").to_list()
2. 获取自定义资源的Logical ID
你报错的原因是 get_logical_id 仅接受 CfnElement 类型的L1底层资源对象,而你传入的 test.cr 是L2级别的封装构造,需要先获取其底层的L1资源实例:
# 先获取底层L1 CfnCustomResource实例 cfn_cr = test.cr.node.default_child # 再调用get_logical_id获取Logical ID cr_logical_id = self.get_logical_id(cfn_cr)
优化建议
你可以把常用属性封装到你的自定义Construct中,简化外部调用:
在 hz_with_delegation 类的__init__方法末尾添加如下代码:
self.physical_id = self.cr.ref self.hosted_zone_id = self.cr.get_att("HostedZoneId") self.name_servers = self.cr.get_att("NameServers")
后续外部调用时直接使用 test.hosted_zone_id 即可,无需重复访问cr属性。
内容的提问来源于stack exchange,提问作者h4k4s4m
相关产品推荐
相关产品推荐

