如何使用CloudFormation创建私有AWS API Gateway?

6
我将尝试创建一个AWS API网关,类型为PRIVATE。这需要一个资源策略,我已经有了,因为我可以通过AWS控制台创建网关。我想知道如何通过CF模板添加资源策略。以下是资源策略的Swagger定义:
x-amazon-apigateway-policy:
  Version: "2012-10-17"
  Statement:
  - Effect: "Deny"
    Principal: "*"
    Action: "execute-api:Invoke"
    Resource: "arn:aws:execute-api:us-east-1:awsAccountId:xxxx/*/*/*"
    Condition:
      StringNotEquals:
        aws:sourceVpc: "vpc-xxxxx"
  - Effect: "Allow"
    Principal: "*"
    Action: "execute-api:Invoke"
    Resource: "arn:aws:execute-api:us-east-1:xxxx:xxxx/*/*/*"

如何在 CF 模板中进行配置 -

AWSTemplateFormatVersion: 2010-09-09
Transform: 'AWS::Serverless-2016-10-31'
Description: G2G Api Template Stack

Resources:
   g2gPrivate:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: 'private-gw'
      EndpointConfiguration:
        Types:
          - PRIVATE
参考 -
https://docs.aws.amazon.com/zh_cn/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html
https://medium.com/@cathmgarcia/aws-sam中基于inline-swagger的条件资源策略管理-816ce946dbb
1个回答

9
您需要在与Name同级的键下(称为Policy)提供策略。
请参考以下链接了解有关JSON格式的详细信息: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-policy
AWSTemplateFormatVersion: 2010-09-09
Transform: 'AWS::Serverless-2016-10-31'
Description: G2G Api Template Stack

Resources:
   g2gPrivate:
    Type: 'AWS::ApiGateway::RestApi'
    Properties:
      Name: 'private-gw'
      EndpointConfiguration:
        Types:
          - PRIVATE
      Policy: !Sub |
        {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Deny",
              "Principal": "*",
              "Action": "execute-api:Invoke",
              "Resource": "arn:aws:execute-api:us-east-1:${AWS::AccountId}:*/*/*/*",
              "Condition": {
                "StringNotEquals": {
                  "aws:sourceVpc": "vpc-xxxxx"
                }
              }
            },
            {
              "Effect": "Allow",
              "Principal": "*",
              "Action": "execute-api:Invoke",
              "Resource": "arn:aws:execute-api:us-east-1:${AWS::AccountId}:*/*/*/*"
            }
          ]
        }


1
我该如何在策略JSON中引用AWS AccountId和APIGateway?有没有使用Sub!来获取AWSAccountId的方法,以及如何在JSON中引用同一网关的Id? - Ani
1
是的,你可以使用!Sub。我已经更新了示例,以确保它能够正常工作。 - Mat
这里有一个小问题,在策略中,“Resource”属性需要ApiId,“xxxx”部分是API ID,所以在这种情况下,我需要先创建网关,然后使用您分享的策略示例修改相同的资源吗? - Ani
3
与其在ARN中提供ApiID,您可以使用通配符“*”。例如arn:aws:execute-api:us-east-1:${AWS::AccountId}:*/*/*/*这样做是安全的,因为策略明确与此API网关相关联。 - Mat
没问题。是的,我已经使用CloudFormation和API Gateway有一段时间了。大部分情况下都很好,但有时候也会让人感到沮丧! - Mat
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接