如何使用cloudformation创建私有AWS Api网关?

时间:2019-09-04 09:45:52

标签: amazon-web-services amazon-cloudformation aws-api-gateway

我正在尝试创建PRIVATE类型的AWS API网关,
这需要一项资源策略,因为我可以从AWS控制台创建网关,因此具有该策略,
我想知道如何通过CF模板添加资源策略-

以下是对资源策略的严格定义-

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/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html

https://medium.com/@cathmgarcia/conditional-resource-policy-on-aws-sam-with-inline-swagger-816ce946dbb

1 个答案:

答案 0 :(得分:3)

您需要在与Policy相同级别的密钥(称为Name)下提供策略。

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-policy

这需要以JSON格式提供。

类似...

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}:*/*/*/*"
            }
          ]
        }