Как получить предварительно назначенный URL-адрес s3 с конечной точкой s3 vp c в режиме без сервера в nodejs - PullRequest
0 голосов
/ 02 февраля 2020

У меня есть приложение aws без сервера в nodejs. Я создал s3 bucket, vp c и конечную точку s3, как показано ниже в serverless.yml

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: eu-west-2 # Europe (London)
  vpcName: vpc-#{AWS::AccountId}-${self:provider.stage}
  privateSubnetAName: privatesubnet-a-${self:service}-${self:provider.stage}
  privateSubnetBName: privatesubnet-b-${self:service}-${self:provider.stage}
  publicSubnetAName: publicsubnet-a-${self:service}-${self:provider.stage}
  vpc:
    securityGroupIds:
      - !Ref SecurityGroup
    subnetIds:
      - !Ref PrivateSubnetB
      - !Ref PrivateSubnetA
  environment:
    S3_BUCKET: resourcesbucket-${self:service}-${self:provider.stage}
  # Add statements to the Lambda function's IAM Role here
  iamManagedPolicies:
    - arn:aws:iam::aws:policy/AmazonS3FullAccess
  iamRoleStatements:
    - Effect: Allow
      Action:
        - ec2:DescribeInstances
        - ec2:StartInstances
        - ec2:StopInstances
        - ec2:RunInstances
      Resource: '*'
    - Effect: Allow
      Action:
        - iam:PassRole
      Resource: '*'
      Condition:
        StringEquals:
          iam:PassedToService: ['ec2.amazonaws.com', 'ec2.amazonaws.com.cn']
    - Effect: Allow
      Action:
        - ec2:CreateTags
      Resource: '*'
      Condition:
        StringEquals:
          ec2:CreateAction: RunInstances

functions:
  query:
    handler: route.reportHandler
    events:
      - http:
          path: query
          method: post
          cors: true
          origin: '*'
          maxAge: 86400

resources:
  Resources:
    S3Bucket:
      Type: 'AWS::S3::Bucket'
      Properties:
        BucketName: ${self:provider.environment.S3_BUCKET}
        BucketEncryption:
          ServerSideEncryptionConfiguration:
            - ServerSideEncryptionByDefault:
                SSEAlgorithm: AES256
        VersioningConfiguration:
          Status: Enabled
        CorsConfiguration:
          CorsRules:
            - AllowedHeaders: ['*']
              AllowedMethods: [GET, PUT]
              AllowedOrigins: ['*']
              Id: CORSRuleId
              MaxAge: '3600'

    S3BucketPolicy:
      Type: AWS::S3::BucketPolicy
      Properties:
        Bucket: !Ref S3Bucket
        PolicyDocument:
          Statement:
            - Effect: Allow
              Action:
                - s3:GetObject
              Resource: 'arn:aws:s3:::${self:provider.environment.S3_BUCKET}/*'
              Principal: '*'
              Condition:
                StringEquals:
                  aws:sourceVpce: !Ref VPC

    # # ======================= Private VPC Configuration ====================
    # # Create a VPC
    VPC:
      Type: AWS::EC2::VPC
      Properties:
        CidrBlock: 172.16.0.0/16
        EnableDnsHostnames: True
        EnableDnsSupport: True
        Tags:
          - Key: name
            Value: ${self:provider.vpcName}

    # # Create a Subnet
    PrivateSubnetA:
      Type: AWS::EC2::Subnet
      Properties:
        CidrBlock: 172.16.2.0/24
        VpcId: !Ref VPC
        AvailabilityZone: ${self:provider.region}a
        Tags:
          - Key: name
            Value: ${self:provider.privateSubnetAName}

    # # Create a Subnet
    PrivateSubnetB:
      Type: AWS::EC2::Subnet
      Properties:
        CidrBlock: 172.16.1.0/24
        VpcId: !Ref VPC
        AvailabilityZone: ${self:provider.region}b
        Tags:
          - Key: name
            Value: ${self:provider.privateSubnetBName}

    # # Create a Subnet
    PublicSubnetA:
      Type: AWS::EC2::Subnet
      Properties:
        CidrBlock: 172.16.3.0/24
        VpcId: !Ref VPC
        AvailabilityZone: ${self:provider.region}a
        Tags:
          - Key: name
            Value: ${self:provider.publicSubnetAName}

    # # Create a Route Table. This will contain a route out to Internet Gateway
    PublicRouteTable:
      Type: AWS::EC2::RouteTable
      Properties:
        VpcId: !Ref VPC

    # Create a Route Table. This will contain a route out to NAT Gateway
    PrivateRouteTable:
      Type: AWS::EC2::RouteTable
      Properties:
        VpcId: !Ref VPC

    # # Create an Elastic IP
    EIP:
      Type: 'AWS::EC2::EIP'
      Properties:
        Domain: vpc

    # # Create the NAT Gateway
    NatGateway:
      Type: 'AWS::EC2::NatGateway'
      Properties:
        AllocationId: !GetAtt 'EIP.AllocationId'
        SubnetId: !Ref PublicSubnetA

    # # Create a route out to NAT Gateway
    Route:
      Type: 'AWS::EC2::Route'
      Properties:
        RouteTableId: !Ref PrivateRouteTable
        DestinationCidrBlock: '0.0.0.0/0'
        NatGatewayId: !Ref NatGateway

    # # Attach Subnet to Route Table
    PrivateSubnetBPrivateRouteAssociation:
      Type: AWS::EC2::SubnetRouteTableAssociation
      Properties:
        RouteTableId: !Ref PrivateRouteTable
        SubnetId: !Ref PrivateSubnetB

    # # Attach Subnet to Route Table
    PrivateSubnetAPrivateRouteAssociation:
      Type: AWS::EC2::SubnetRouteTableAssociation
      Properties:
        RouteTableId: !Ref PrivateRouteTable
        SubnetId: !Ref PrivateSubnetA

    # # Attach Subnet to Route Table
    SubnetAPublicRouteAssociation:
      Type: AWS::EC2::SubnetRouteTableAssociation
      Properties:
        RouteTableId: !Ref PublicRouteTable
        SubnetId: !Ref PublicSubnetA

    # # Creat a security group and open port 80 and 443 in bound and out bound
    SecurityGroup:
      Type: AWS::EC2::SecurityGroup
      Properties:
        GroupDescription: SecurityGroup-#{AWS::AccountId}-${self:provider.stage}
        VpcId: !Ref VPC
        SecurityGroupIngress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: 0.0.0.0/0
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: 0.0.0.0/0
        SecurityGroupEgress:
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: 0.0.0.0/0
          - IpProtocol: tcp
            FromPort: 443
            ToPort: 443
            CidrIp: 0.0.0.0/0
          - IpProtocol: tcp
            FromPort: 3306
            ToPort: 3306
            CidrIp: 0.0.0.0/0

    # # Create an Internet Gateway
    InternetGateway:
      Type: AWS::EC2::InternetGateway

    # # Attach the internet gateway to the VPC
    VPCInternetGatewayAttachment:
      Type: AWS::EC2::VPCGatewayAttachment
      Properties:
        InternetGatewayId: !Ref InternetGateway
        VpcId: !Ref VPC

    # # Create a route out to Internet Gateway
    PublicRoute:
      Type: AWS::EC2::Route
      DependsOn: VPCInternetGatewayAttachment
      Properties:
        RouteTableId: !Ref PublicRouteTable
        DestinationCidrBlock: 0.0.0.0/0
        GatewayId: !Ref InternetGateway

    # # create S3 endpoint
    s3Endpoint:
      Type: AWS::EC2::VPCEndpoint
      Properties:
        PolicyDocument:
          Statement:
            - Effect: Allow
              Principal: '*'
              Action:
                - 's3:*'
              Resource:
                - '*'
        RouteTableIds:
          - !Ref PrivateRouteTable
        ServiceName: !Sub com.amazonaws.${self:provider.region}.s3
        VpcId: !Ref VPC

    # # ======================= Private VPC Configuration ====================

, которую я разработал для генерации предварительно назначенного URL-адреса s3 с помощью приведенного ниже кода.

import AWS from 'aws-sdk';

const s3 = new AWS.S3({ signatureVersion: 'v4' });
const bucket = process.env.S3_BUCKET;

const signedUrl = async fileName => {
  const params = {
    Bucket: bucket,
    Key: `uploads/${fileName}`,
    Expires: 3600
  };
  const s3signedUrl = await new Promise((resolve, reject) => {
    s3.getSignedUrl('putObject', params, (err, url) => {
      if (err) reject(err);
      resolve(url);
    });
  });
  return s3signedUrl;
};

export default signedUrl;

VP C создается, а также конечная точка s3 и политика сегмента в сегменте s3. что я не понимаю, так это то, как я могу получить предварительно назначенный URL через конечную точку s3. Я получаю предварительно назначенный URL-адрес, как показано ниже: https://resourcesbucket-reports-shamila.s3.eu-west-2.amazonaws.com/uploads/test1.png?X-Amz-Algorithm=AWS4-FxBTrgAZ4lO4PUA2n7MxyhRUEgZOnZyGnvXRPqMiiWEoayD5%2 ...

Загрузка файлов успешно осуществляется через этот предварительно назначенный URL-адрес. Как получить предопределенный URL-адрес через созданную конечную точку vp c s3?

...