无法为CfnResource添加对CustomResource的dependsOn依赖问题
问题解决:CfnResource无法添加对CustomResource的dependsOn依赖
问题描述
执行代码时触发类型错误:
Argument of type 'CustomResource' is not assignable to parameter of type 'CfnResource'
核心原因是CfnResource.addDependsOn()方法仅接受**底层CloudFormation资源(CfnResource类型)**作为参数,而cdk.CustomResource是AWS CDK的二级(L2)构造,并非直接的CfnResource实例。
解决方案
通过CustomResource.node.defaultChild获取其对应的底层CfnCustomResource资源,转换类型后传入addDependsOn即可解决:
修改后的完整代码:
const cfnRawTable = new timestream.CfnTable(this, 'MyCfnTableRaw', { databaseName: dbName, // 可选配置 magneticStoreWriteProperties: { enableMagneticStoreWrites: true, }, retentionProperties: { magneticStoreRetentionPeriodInDays: '1825', memoryStoreRetentionPeriodInHours: '8640', }, tableName: rawtable, }) let insertionLambda = new cdk.CustomResource(this, 'insertionlambda', { serviceToken: 'arn:aws:lambda:' + cdk.Fn.ref('region') + '738234497474:function:timestreaminsertion-' + cdk.Fn.ref('env'), }) // 获取CustomResource的底层Cfn资源并添加依赖 const cfnCustomResource = insertionLambda.node.defaultChild as cdk.CfnResource; cfnRawTable.addDependsOn(cfnCustomResource);
补充说明
node.defaultChild会返回构造对应的核心底层CloudFormation资源,对于CustomResource来说,这个资源就是CfnCustomResource,属于CfnResource的子类。- 类型断言
as cdk.CfnResource是为了通过TypeScript的类型检查,保证代码正常编译。
内容的提问来源于stack exchange,提问作者Ilijanovic
相关产品推荐
相关产品推荐

