服务
关于
CloudProse博客
开发人员经验

Amplify Console-AWS上静态托管的动态解决方案

永远不要再管理您自己的CloudFront / S3存储桶!
迈克尔·巴尼(Michael Barney)Trek10
迈克尔·巴尼 | 2020年2月12日

熟悉的故事

您需要在AWS上托管一个静态站点,因此以下 CloudFormation优先开发,您编写了一个CloudFormation模板来定义这些资源:

  • S3存储桶-用于存储站点
  • CloudFront分发-从S3存储桶提供内容
  • CloudFront原始访问身份-为分发提供信任的实体
  • S3存储桶策略-信任CloudFront原始访问身份
  • 几个Route53记录集-为分发设置DNS

开发此模板需要花费时间,并且每次在CloudFront发行版上进行迭代时,您都必须等待20到30分钟才能完成发布。此障碍可能是影响您生产力的最大因素之一。

即使完成模板(或从在线示例中拉出模板),您仍需要在前端代码上设置CI才能将构建的站点上载到创建的S3存储桶。之后,您需要创建一个 CloudFront缓存无效 以确保您的用户获得了正确的资产。您甚至可能需要构建一些自定义Lambda @ Edge函数来处理重定向或重写,具体取决于您网站的结构。这将增加另一种痛苦的开发人员体验,因为每次功能更新时您都必须等待20-30分钟,以便CloudFront发行版可以完成更新。

必须有另一种方式,对吗?对。

放大控制台-正确的一步

不要与AWS“ Amplify”伞下的其他服务相混淆,Amplify Console提供了一种使用完整CI / CD托管您的网站的方法,几乎​​可以完全(无服务器)为您管理。因此,让我们启动并运行一个网站。

我们将遵循CloudFormation优先开发,并从模板开始。 Amplify Console最基本的资源类型是 AWS::Amplify::App resource. The only required property 这里 is Name. While you should let CloudFormation name your resources in most cases, 放大应用 names are not required to be unique. The most basic amplify app would look like this:

Resources:
  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      Name: my-website

此CloudFormation将创建一个在CI方面不提供太多功能的应用程序;每当您要手动部署某些内容时,都必须上传您的网站。因此,让我们修复一下:

Parameters:
  Repository:
    Type: String
    Description: GitHub Repository URL
  OauthToken:
    Type: String
    Description: GitHub Repository URL
    NoEcho: true
  Branch:
    Type: String
    Description: The name of the branch to deploy off of
Resources:
  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      Name: my-website
      Repository: !Ref Repository
      OauthToken: !Ref OauthToken
      AccessToken: !Ref OauthToken
  AmplifyBranch:
    Type: AWS::Amplify::Branch
    Properties:
      BranchName: !Ref Branch
      AppId: !GetAtt AmplifyApp.AppId
      EnableAutoBuild: true

Here we've added a Repository and an OauthToken property to the amplify app. The token will be used to create a webhook and read-only deploy key for your third-party provider. For Github, the token will be a "Personal Access Token." For Bitbucket, unfortunately, CloudFormation is not yet well supported. As for the repository, this is expected to be the https url to the repository, without the trailing .git.

我们还添加了一个 AWS::Amplify::Branch 资源。 Amplify Console将git“分支”视为部署“环境”。对于大多数已连接的应用程序,分支是一个环境,但是对于未连接的应用程序,此术语可能会造成混淆;只要记住分支==环境。

现在,每当我们将提交推送到存储库时,Amplify Console都会选择该提交并拆分部署。

那么自定义域呢?

Parameters:
  Repository:
    Type: String
    Description: GitHub Repository URL
  OauthToken:
    Type: String
    Description: GitHub Repository URL
    NoEcho: true
  Branch:
    Type: String
    Description: The name of the branch to deploy off of
  Domain:
    Type: String
    Description: Domain name to host application
Resources:
  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      Name: my-website
      Repository: !Ref Repository
      OauthToken: !Ref OauthToken
      AccessToken: !Ref OauthToken
  AmplifyBranch:
    Type: AWS::Amplify::Branch
    Properties:
      BranchName: !Ref Branch
      AppId: !GetAtt AmplifyApp.AppId
      EnableAutoBuild: true
  AmplifyDomain:
    Type: AWS::Amplify::Domain
    Properties:
      DomainName: !Ref Domain
      AppId: !GetAtt AmplifyApp.AppId
      SubDomainSettings:
        - BranchName: !GetAtt AmplifyBranch.BranchName
          Prefix: ''
        - BranchName: !GetAtt AmplifyBranch.BranchName
          Prefix: www

We added a Domain parameter that feeds right into an AWS::Amplify::Domain resource. This resource enables you to connect a custom domain to an amplify app. If you are using Route53 for DNS, and the hosted zone for the domain you want is in the same account, a record set will automatically be added for you. You can even configure prefixes, like the common www prefix, as shown in the template.

此资源还为您提供ACM SSL证书。只要它位于同一帐户中,它将再次自动对同一域的Route53托管区域使用DNS验证。请注意,完成证书验证可能需要几分钟。

就是这样;现在,您正在使用完全托管的前端CI / CD平台,而无需配置自己的CloudFront发行版,ACM证书或Route53记录。不仅如此,Amplify Console还提供许多功能。

我们如何在Trek10上使用Amplify Console?

In a recent project that was under a multi-account strategy, we had a dev, staging, and production account. We set up a process to deploy the amplify CloudFormation template in each account. The production account's app targeted the master branch, the staging account's app targeted a test branch, and the dev account's app targeted a develop branch. We also configured feature branch deployments on the dev account's app, so we could have frontend devs work on features in parallel, without stepping on any other frontend dev's work. Since Amplify Console provides you with continuous deployment, this is our frontend CI/CD platform.

自定义构建步骤

Amplify Console will automatically detect what framework you're using, whether it's React, Angular, Vue, or even site generators like VuePress, Jekyll, and Gatsby. However, if you have other build requirements, you can place a buildspec-like file in the root of your git repository called amplify.yml. This file follows a buildspec-like format, and is documented 这里. The 放大应用 can also contain the build steps if that's more desirable. Just include the buildspec under Properties. You can also include an IAMServiceRole property to give your build IAM permissions:

  AmplifyRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: amplify.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: Amplify
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: amplify:*
                Resource: '*'
  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      Name: my-website
      Repository: !Ref Repository
      OauthToken: !Ref OauthToken
      AccessToken: !Ref OauthToken
      IAMServiceRole: !GetAtt AmplifyRole.Arn
      建立Spec: |
        version: 1.0
        frontend:
          phases:
            ...

您还可以向构建中添加环境变量,以便可以注入诸如API url环境变量之类的内容。对于React应用,它看起来像这样:

  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      ...
      EnvironmentVariables:
        - Name: REACT_APP_API_URL
          Value: !Sub //api.${Domain}

自动分支创建

With Amplify Console, you can configure your app so that the branch that gets created under a specific wildcard match (like feature/*) will automatically create a new branch/environment and deploy that branch to it. To configure this in CloudFormation:

  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      AutoBranchCreationConfig:
        AutoBranchCreationPatterns:
          - feature/*
        BasicAuthConfig:
          EnableBasicAuth: True
          Password: password
          Username: admin
        EnableAutoBranchCreation: True
        EnableAutoBuild: True
        Stage: PULL_REQUEST # PRODUCTION | BETA | DEVELOPMENT | EXPERIMENTAL | PULL_REQUEST

拉取请求预览

此功能仅适用于私有GitHub存储库。您必须安装 放大应用 第一。

With Amplify Console, you can configure your app so that every pull request deploys to a unique environment, with a unique preview url. When the pull request is closed, the unique environment will be deleted with it. To set this up in CloudFormation, add the EnablePullRequestPreview and PullRequestEnvironmentName properties to your AWS::Amplify::Branch resource.

  AmplifyBranch:
    Type: AWS::Amplify::Branch
    Properties:
      EnablePullRequestPreview: True
      PullRequestEnvironmentName: prenv

Alternatively you can set this up in the AutoBranchCreationConfig section of an AWS::Amplify::App resource, which will apply to dynamically-created amplify branches:

  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      AutoBranchCreationConfig:
        EnablePullRequestPreview: True
        PullRequestEnvironmentName: prenv

电子邮件通知

CloudFormation尚不支持此功能,但是您可以配置电子邮件通知以接收有关应用程序部署的更新。当构建开始,失败和成功时,您会收到电子邮件,逐个分支。

在您的应用程序的Amplify控制台中,选择左侧的“电子邮件通知”,然后您可以在该处管理应该在每个分支接收通知的电子邮件。

基本认证

You can configure basic auth to password-protect your sites. This can be applied to the entire app, or just the auto-created environments (such as pull-request previews or environments created from the AutoBranchCreationConfig).

访问日志

使用Amplify Console,您可以查看网站的访问日志。在控制台中,您可以单击“访问日志”部分,并查看应用程序下每个域源的访问日志。这包括日期,时间,主机标头,状态和用户代理。您可以在特定时间范围内查询,甚至可以csv格式下载日志。该控制台还允许您搜索日志以找到所需的确切信息。

重写和重定向

You can use redirects to reroute navigation from one url to another, which comes in handy when developing a Single Page App like a react app where you want navigation to be routed to /index.html. The 文件资料 具有通用的重写和重定向规则。这样可以省去大多数Lambda @ Edge功能,而所需的运营成本要低得多。

重定向分为四个部分:

  • Source -要求的地址
  • Target -服务内容的地址
  • Status -重定向的类型(例如200重写或永久重定向301)
  • Condition -两个字母的国家/地区代码,可让您按地区细分受众群体

要在CloudFormation中进行设置:

  AmplifyApp:
    Type: AWS::Amplify::App
    Properties:
      ...
      CustomRules:
        - Source: /documents
          Target: /documents/us/
          Condition: <US>
          Status: '302'

即时缓存无效

通过放大部署的应用程序可从中受益 即时缓存失效。构建完成并部署您的应用后,Amplify将立即使为网站提供的缓存无效。

结论

Amplify Console可以做很多事情,包括运行 在各种设备上测试和渲染应用的屏幕截图。就让AWS管理繁重的工作而言,它提供了很多价值,因此您不必这样做。如果您有静态站点,请利用Amplify Console,再也不用担心CloudFront,存储桶权限或再次使缓存失效!

作者
迈克尔·巴尼(Michael Barney)Trek10
迈克尔·巴尼

DevOps工程师

Michael的职业生涯始于无服务器世界,他刚从大学毕业就加入了Trek10团队-真正的无服务器本地人。