CDK跨栈引用Sagemaker端点时,如何生成全小写ARN?
解决方案
方法1:用CloudFormation内置函数构造全小写ARN
直接通过Fn.sub结合Fn.lower手动构造ARN,避开formatArn无法处理动态值转换的问题:
myFunction.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ['sagemaker:InvokeEndpoint'], resources: [ Fn.sub( 'arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint/${lowerEndpointName}', { lowerEndpointName: Fn.lower(endpoint.attrEndpointName), } ), ], }));
原理
Fn.lower(endpoint.attrEndpointName)是CloudFormation内置函数,支持对跨栈引用的动态端点名称做全小写转换Fn.sub将转换后的小写名称代入ARN模板,生成符合Lambda权限要求的资源路径
方法2:创建端点时指定全小写名称
如果允许自定义端点名称(非完全依赖CDK自动生成),可以在创建CfnEndpoint时直接生成全小写的唯一名称,后续跨栈引用无需额外转换:
// 生成唯一的全小写端点名称 const endpointName = Names.uniqueId(this).toLowerCase(); const endpoint = new CfnEndpoint(this, "Endpoint", { endpointConfigName: endpointConfig.attrEndpointConfigName, endpointName: endpointName, }); // 跨栈引用时直接使用全小写名称构造ARN myFunction.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ['sagemaker:InvokeEndpoint'], resources: [Stack.of(this).formatArn({ service: 'sagemaker', resource: 'endpoint', resourceName: endpointName, })], }));
原理
Names.uniqueId(this)生成CDK默认的唯一标识符,通过toLowerCase()转为全小写- 手动指定
endpointName后,生成的ARN自然包含全小写名称,权限配置无需额外处理
为什么之前的Fn::Transform方法失败?
AWS CloudFormation的String转换宏要求InputString必须是静态值、CloudFormation输入参数或简单字面量,而跨栈引用的endpoint.attrEndpointName属于动态导出值(本质是Fn::ImportValue),不符合宏的参数要求,因此触发报错。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

