首页 > 解决方案 > 从私有子网中的 Fargate 容器访问 DynamoDB

问题描述

我正在为使用FastAPI进行 API 设计的项目构建以下基础架构。这里有两个微服务:/user/* 和 /admin/*,它们读取和更新存储在 DynamoDB 中的数据。

设置如下:我有一个带有 2 个可用区的 VPC,每个可用区托管一个公共子网和一个私有子网。每个公有子网都有一个 NAT 网关,用于同一 AZ 中的私有子网。Internet 网关连接到 VPC。为 DynamoDB 创建了一个 VPC 终端节点。ECS 集群是以 Fargate 为启动类型创建的,服务在两个私有子网中运行。

CloudFormation 模板构建,但 API 请求返回内部服务器错误。我认为问题在于容器没有正确访问 DynamoDB 表的权限。

以下是我创建并附加到 ECS 容器 (ECSTaskExecutionRole) 的 IAM 角色:

ECSTaskExecutionRole:
    Type: AWS::IAM::Role
    # Role for ECS task
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: [ecs-tasks.amazonaws.com]
            Action: ['sts:AssumeRole']
      Path: /
      Policies:
        - PolicyName: AmznECSTaskExecutionRolePolicy
          PolicyDocument:
            Statement:
            - Effect: Allow
              Action:
                # ECS tasks to download images from ECR
                - ecr:GetAuthorizationToken
                - ecr:BatchCheckLayerAvailability
                - ecr:GetDownloadUrlForLayer
                - ecr:BatchGetImage
                # ECS tasks to upload logs to CloudWatch
                - logs:CreateLogGroup
                - logs:CreateLogStream
                - logs:PutLogEvents
                - logs:DescribeLogStreams
                # ECS tasks to use DynamoDB
                - dynamodb:Batch*
                - dynamodb:Delete*
                - dynamodb:DescribeTable
                - dynamodb:GetItem
                - dynamodb:PutItem
                - dynamodb:Update*
              Resource: '*'

以下是 DynamoDB 的 VPC 终端节点:

DynamoDBVpcEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref VPC
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.dynamodb"
      VpcEndpointType: Gateway
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action: '*'
            Principal: '*'
            Resource: '*'
      RouteTableIds:
        - !Ref VPCPrivateRouteTable1
        - !Ref VPCPrivateRouteTable2

我还确保私有子网的路由表包含一对 DynamoDB 终端节点。

任何帮助将不胜感激!谢谢你。

标签: amazon-dynamodbamazon-cloudformationamazon-ecsamazon-vpcaws-fargate

解决方案


推荐阅读