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

CloudFormation中如何配置仅特定API Gateway可扮演指定IAM角色?

解决方案

要实现仅新建的API Gateway能扮演指定IAM角色,你需要通过**条件判断(Condition)**来限制信任策略,而不是替换Principal.Service的值。具体说明和修正后的模板如下:

关键注意点

  1. 不能将API Gateway的ARN填入Principal.Service字段——该字段仅用于指定AWS服务主体(如apigateway.amazonaws.com),而非具体资源的ARN。
  2. AWS::ApiGatewayV2::Api资源没有直接可引用的Arn属性,需通过API ID手动构造ARN,格式为:arn:aws:apigateway:${AWS::Region}::/apis/${API_ID},其中API_ID可通过Ref获取该资源的ID。

修正后的CloudFormation模板

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  ApiGatewayHttpApi:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: my_api_gateway
      ProtocolType: HTTP

  ApiGatewayRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: my_api_gateway_role
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: apigateway.amazonaws.com
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                # 构造目标API Gateway的ARN,限制仅该API能扮演角色
                aws:SourceArn: !Sub "arn:aws:apigateway:${AWS::Region}::/apis/${ApiGatewayHttpApi}"

原理说明

通过aws:SourceArn条件,IAM会验证发起AssumeRole请求的来源是否为指定的API Gateway ARN,从而确保只有你新建的这个API Gateway能够使用该角色,其他API Gateway无法触发此权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:42:05