You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AwsCustomResource的OnCreate与OnUpdate中使用不同SDK服务并获取输出值?

解决AwsCustomResource跨操作获取不同输出字段的问题

你可以通过统一两个操作的输出字段名来解决这个问题,利用outputPaths的对象语法重命名OnCreate的输出键,让它和OnUpdate的输出键保持一致,这样就能用同一个getResponseField调用拿到结果。

具体修改如下:

const getRestApiBasePathMappings = new custom_resources.AwsCustomResource(this, `GetRestApiBasePathMappings`, {
  policy: custom_resources.AwsCustomResourcePolicy.fromStatements([
    new iam.PolicyStatement({ actions: ['apigateway:GET'], resources: ['*'] }),
    new iam.PolicyStatement({ actions: ['ssm:GetParameter'], resources: ['*'] }), // 修正原代码中SSM权限的拼写错误
  ]),
  onCreate: {
    service: 'SSM',
    action: 'getParameter',
    parameters: {
      Name: `${activeStageParameter}/${this.environmentName}`,
    },
    physicalResourceId: custom_resources.PhysicalResourceId.of(Date.now().toString()),
    // 用对象语法将SSM返回的Parameter.Value重命名为stage
    outputPaths: { 'stage': 'Parameter.Value' },
  },
  onUpdate: {
    service: 'APIGateway',
    action: 'getBasePathMapping',
    parameters: { basePath: 'rest', domainName: domainName },
    physicalResourceId: custom_resources.PhysicalResourceId.of(Date.now().toString()),
    outputPaths: ['stage'], // 保持原数组语法,输出键统一为stage
  },
});

// 现在直接获取统一后的stage字段即可
const restStage = getRestApiBasePathMappings.getResponseField('stage');

注意:原代码中IAM策略里的SSM权限动作写错了,正确的应该是ssm:GetParameter而非ssm:GET,不修正会导致权限不足的错误。

如果因特殊场景无法统一输出键名,也可以通过CloudFormation条件函数判断当前是创建还是更新操作,分别获取对应字段,但这种方式复杂度更高,统一键名是最简洁的解决方案。

内容的提问来源于stack exchange,提问作者Loaf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:37:05