Как ссылаться на доменное имя CloudFront при создании AWS::S3:: набора записей в CloudFormation / без сервера?

#amazon-cloudformation #amazon-cloudfront #serverless

#aws-cloudformation #amazon-cloudfront #без сервера

Вопрос:

У меня есть проект, в котором есть дистрибутив cloudfront для обслуживания некоторых данных из корзины. Я использую бессерверную платформу, но я думаю, что это в основном вопрос CloudFormation.

Я хотел бы создать запись A в размещенном домене Route53 (домен третьего уровня, если это имеет значение, т.Е. dashboard.domain.com указывает на Route53, и я пытаюсь добавить.dashboard.domain.com ).

Я просто не могу понять, как ссылаться на выходные данные из ресурса CloudFront?

Это то, что у меня есть прямо сейчас, и это работает, потому что все это статично. Однако мне нужно автоматически указать правильный домен cloud front, который будет создан другим ресурсом. Я полагаю, что это какой-то тип GetAttr, который я могу сделать, но я просто не могу заставить его работать.

     DNSRecords: 
      Type: AWS::Route53::RecordSetGroup
      Properties:
        HostedZoneId: Z09193931V4YGJEPVMLG1
        RecordSets:
          - Name: prod.dashboard.domain.com
            Type: A
            AliasTarget:
              HostedZoneId: Z2FDTNDATAQYW2
              DNSName: someid.cloudfront.net

  
     WebAppCloudFrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          Origins:
            - DomainName:
                Fn::Join: [
                  "", [
                    { "Ref": "WebAppS3Bucket" },
                    ".s3.amazonaws.com"
                  ]
                ]
              ## An identifier for the origin which must be unique within the distribution
              Id: WebApp
              CustomOriginConfig:
                HTTPPort: 80
                HTTPSPort: 443
                OriginProtocolPolicy: https-only
          Enabled: 'true'
          ## Uncomment the following section in case you are using a custom domain
          Aliases:
            - ${self:provider.stage}.dashboard.domain.com
          DefaultRootObject: index.html
          ## Since the Single Page App is taking care of the routing we need to make sure ever path is served with index.html
          ## The only exception are files that actually exist e.h. app.js, reset.css
          CustomErrorResponses:
            - ErrorCode: 404
              ResponseCode: 200
              ResponsePagePath: /index.html
          DefaultCacheBehavior:
            AllowedMethods:
              - DELETE
              - GET
              - HEAD
              - OPTIONS
              - PATCH
              - POST
              - PUT
            ## The origin id defined above
            TargetOriginId: WebApp
            ## Defining if and how the QueryString and Cookies are forwarded to the origin which in this case is S3
            ForwardedValues:
              QueryString: 'false'
              Cookies:
                Forward: none
            ## The protocol that users can use to access the files in the origin. To allow HTTP use `allow-all`
            ViewerProtocolPolicy: redirect-to-https
          ## The certificate to use when viewers use HTTPS to request objects.
          ViewerCertificate:
            AcmCertificateArn:
              Ref: SSLCertificate
            SslSupportMethod: sni-only
            MinimumProtocolVersion: TLSv1
  

РЕДАКТИРОВАТЬ: обновлено, чтобы включить WebAppCloudFrontDistribution

Ответ №1:

Вы не предоставили свое AWS::CloudFront::Distribution определение ресурса, поэтому я могу использовать его только на примере.

 MyCloudFrontDistro:
  Type: AWS::CloudFront::Distribution
  Properties:
    # some properties
  

Затем вы можете изменить свой DNSRecords

     DNSRecords: 
      Type: AWS::Route53::RecordSetGroup
      Properties:
        HostedZoneId: Z09193931V4YGJEPVMLG1
        RecordSets:
          - Name: prod.dashboard.domain.com
            Type: A
            AliasTarget:
              HostedZoneId: !Ref MyCloudFrontDistro
              DNSName: !GetAtt MyCloudFrontDistro.DomainName
  

Ответ №2:

     WebAppCloudFrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          Origins:
            - DomainName:
                Fn::Join: [
                  "", [
                    { "Ref": "WebAppS3Bucket" },
                    ".s3.amazonaws.com"
                  ]
                ]
              ## An identifier for the origin which must be unique within the distribution
              Id: WebApp
              CustomOriginConfig:
                HTTPPort: 80
                HTTPSPort: 443
                OriginProtocolPolicy: https-only
          Enabled: 'true'
          Aliases:
            - ${self:provider.stage}.dashboard.domain.com
          DefaultRootObject: index.html
          CustomErrorResponses:
            - ErrorCode: 404
              ResponseCode: 200
              ResponsePagePath: /index.html
          DefaultCacheBehavior:
            AllowedMethods:
              - DELETE
              - GET
              - HEAD
              - OPTIONS
              - PATCH
              - POST
              - PUT
            TargetOriginId: WebApp
            ForwardedValues:
              QueryString: 'false'
              Cookies:
                Forward: none
            ## The protocol that users can use to access the files in the origin. To allow HTTP use `allow-all`
            ViewerProtocolPolicy: redirect-to-https
          ## The certificate to use when viewers use HTTPS to request objects.
          ViewerCertificate:
            AcmCertificateArn:
              Ref: SSLCertificate
            SslSupportMethod: sni-only
            MinimumProtocolVersion: TLSv1
            
          ## Uncomment the following section in case you want to enable logging for CloudFront requests
          # Logging:
          #   IncludeCookies: 'false'
          #   Bucket: mylogs.s3.amazonaws.com
          #   Prefix: myprefix

Resources:
    DNSRecords: 
      Type: AWS::Route53::RecordSetGroup
      Properties:
        HostedZoneName: dashboard.domain.com.
        RecordSets:
          - Name: ${self:provider.stage}.dashboard.domain.com
            Type: A
            AliasTarget:
              HostedZoneId: Z2FDTNDATAQYW2
              DNSName: !GetAtt WebAppCloudFrontDistribution.DomainName
  

Вот рабочее решение для меня, обратите внимание на некоторые моменты.

  • HostedZoneId Z2FDTNDATAQYW2 является специальным для домена cloudfront. Его необходимо использовать при ссылке на ресурс облачного интерфейса.
  • В имени HostedZoneName необходимо включить пробел в конце (если вы используете его по сравнению с идентификатором HostedZoneId). В моем случае у меня есть настройка домена до формирования облака.