さて、前回は静的WEBサイトのホスティングをAmplifyで実施してみました。
S3で静的WEBサイトのホスティングを行うよりもGitを使うことができるので、今時の制作フローにはマッチするのではと思います。

そんなわけで今回は、静的ではない動的なWEBサイトをJavascriptベースで特にフレームワークを選択しない場合の、
フルスタックなWEBアプリケーションをAmplifyでホスティングする手順を
Amplifyの公式チュートリアルを見ながら実践してみたので、
その内容を紹介していきます。

まずはローカル端末上で以下を実施します。

$ sudo npm install -g @aws-amplify/cli

amplifyのコマンドが使えるようになるので以下を実行。
(※/usr/local/bin/amplify)

$ amplify configure

リージョン、IAMユーザを入力します。

Specify the AWS Region
? region:  # Your preferred region
Specify the username of the new IAM user:
? user name:  # User name for Amplify IAM user
Complete the user creation using the AWS console

アクセスキー、シークレットキー、AWSのプロファイル名を入力します。
(※今回が初回であればdefaultでも良いですが、既に複数の案件が稼働していてVPCを分けたり、権限など制御している場合は別プロファイル名が良いでしょう。)

Enter the access key of the newly created user:
? accessKeyId:  # YOUR_ACCESS_KEY_ID
? secretAccessKey:  # YOUR_SECRET_ACCESS_KEY
This would update/create the AWS Profile in your local machine
? Profile Name:  # (default)

Successfully set up the new user.

上記情報はローカル上の.aws/config、.aws/credentialsに記載されます。

次に以下を実行します。

$ mkdir -p amplify-js-app/src && cd amplify-js-app
$ touch package.json index.html webpack.config.js src/app.js

上記を実行すると以下のファイル、ディレクトリが生成されます。

amplify-js-app
├── index.html
├── package.json
├── src
│   └── app.js
└── webpack.config.js

package.jsonファイルに以下をコピー&ペーストします。

{
  "name": "amplify-js-app",
  "version": "1.0.0",
  "description": "Amplify JavaScript Example",
  "dependencies": {
    "aws-amplify": "latest"
  },
  "devDependencies": {
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "copy-webpack-plugin": "^6.1.0",
    "webpack-dev-server": "^3.1.5"
  },
  "scripts": {
    "start": "webpack && webpack-dev-server --mode development",
    "build": "webpack"
  }
}

以下コマンドで依存パッケージをインストールします。

$ npm install

index.htmlに以下をコピー&ペーストします。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Amplify Framework</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      html, body { font-family: "Amazon Ember", "Helvetica", "sans-serif"; margin: 0; }
      a { color: #ff9900; }
      h1 { font-weight: 300; }
      hr { height: 1px; background: lightgray; border: none; }
      .app { width: 100%; }
      .app-header { color: white; text-align: center; background: linear-gradient(30deg, #f90 55%, #ffc300); width: 100%; margin: 0 0 1em 0; padding: 3em 0 3em 0; box-shadow: 1px 2px 4px rgba(0, 0, 0, 0.3); }
      .app-logo { width: 126px; margin: 0 auto; }
      .app-body { width: 400px; margin: 0 auto; text-align: center; }
      .app-body button { background-color: #ff9900; font-size: 14px; color: white; text-transform: uppercase; padding: 1em; border: none; }
      .app-body button:hover { opacity: 0.8; }
    </style>
  </head>

  <body>
    <div class="app">
      <div class="app-header">
        <div class="app-logo">
          <img
            src="https://aws-amplify.github.io/images/Logos/Amplify-Logo-White.svg"
            alt="AWS Amplify"
          />
        </div>
        <h1>Welcome to the Amplify Framework</h1>
      </div>
      <div class="app-body">
        <h1>Mutation Results</h1>
        <button id="MutationEventButton">Add data</button>
        <div id="MutationResult"></div>
        <hr />

        <h1>Query Results</h1>
        <div id="QueryResult"></div>
        <hr />

        <h1>Subscription Results</h1>
        <div id="SubscriptionResult"></div>
      </div>
    </div>
    <script src="main.bundle.js"></script>
  </body>
</html>

webpack.config.jsに以下をコピー&ペーストします。

const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/app.js',
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
    devServer: {
        contentBase: './dist',
        overlay: true,
        hot: true
    },
    plugins: [
        new CopyWebpackPlugin({
            patterns: ['index.html']
        }),
        new webpack.HotModuleReplacementPlugin()
    ]
};

以下を実行します。

$ npm start

上記を実行すると、http://xxx.xxx.xxx.xxx:8080にアクセスを促すテキストが流れますが、しかし、筆者環境では上記にアクセスしても以下のようなメッセージが出てWEBサイトは表示されませんでした。

ERROR 405: Cannot download charts index from server: http://xxx.xxx.xxx.xxx:8080/api/v1/charts

次に以下コマンドを実行します。

$ amplify init

以下、必要情報を埋めていきます。

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project amplifyjsapp
? Enter a name for the environment dev
? Choose your default editor: Vim (via Terminal, Mac OS only)
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using none
? Source Directory Path:  src
? Distribution Directory Path: dist
? Build Command:  npm run-script build
? Start Command: npm run-script start
Using default provider  awscloudformation


For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use amplifytest_osmaniax
Adding backend environment dev to AWS Amplify Console app: doq1sshw34d2q
⠇ Initializing project in the cloud...

CREATE_IN_PROGRESS amplify-amplifyjsapp-dev-222121 AWS::CloudFormation::Stack Sun Nov 15 2020 22:21:22 GMT+0900 (日本標準時) User Initiated
CREATE_IN_PROGRESS UnauthRole                      AWS::IAM::Role             Sun Nov 15 2020 22:21:27 GMT+0900 (日本標準時)               
CREATE_IN_PROGRESS DeploymentBucket                AWS::S3::Bucket            Sun Nov 15 2020 22:21:27 GMT+0900 (日本標準時)               
CREATE_IN_PROGRESS AuthRole                        AWS::IAM::Role             Sun Nov 15 2020 22:21:27 GMT+0900 (日本標準時)               
⠋ Initializing project in the cloud...

CREATE_IN_PROGRESS AuthRole         AWS::IAM::Role  Sun Nov 15 2020 22:21:28 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole       AWS::IAM::Role  Sun Nov 15 2020 22:21:29 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Sun Nov 15 2020 22:21:29 GMT+0900 (日本標準時) Resource creation Initiated
⠦ Initializing project in the cloud...

CREATE_COMPLETE AuthRole   AWS::IAM::Role Sun Nov 15 2020 22:21:46 GMT+0900 (日本標準時) 
CREATE_COMPLETE UnauthRole AWS::IAM::Role Sun Nov 15 2020 22:21:47 GMT+0900 (日本標準時) 
⠹ Initializing project in the cloud...

CREATE_COMPLETE DeploymentBucket AWS::S3::Bucket Sun Nov 15 2020 22:22:00 GMT+0900 (日本標準時) 
⠸ Initializing project in the cloud...

CREATE_COMPLETE amplify-amplifyjsapp-dev-222121 AWS::CloudFormation::Stack Sun Nov 15 2020 22:22:03 GMT+0900 (日本標準時) 
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add <category>" will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

デプロイに近づきました。
ステータスを見てみますと空っぽですね。

$ amplify status

Current Environment: dev

| Category | Resource name | Operation | Provider plugin |
| -------- | ------------- | --------- | --------------- |

一旦、PUSHしてみました。「amplify push」を実行です。
しかし、特に変更してない場合は、何も変更がなかったと言われます。

$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name | Operation | Provider plugin |
| -------- | ------------- | --------- | --------------- |

No changes detected

次に「amplify hosting add」を実行します。

$ amplify hosting add
? Select the plugin module to execute Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
? Choose a type Manual deployment

You can now publish your app using the following command:

Command: amplify publish

これで「amplify publish」を実行します。

$ amplify publish
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name  | Operation | Provider plugin   |
| -------- | -------------- | --------- | ----------------- |
| Hosting  | amplifyhosting | Create    | awscloudformation |
? Are you sure you want to continue? Yes
⠙ Updating resources in the cloud. This may take a few minutes...

UPDATE_IN_PROGRESS amplify-amplifyjsapp-dev-222121 AWS::CloudFormation::Stack Sun Nov 15 2020 22:27:32 GMT+0900 (日本標準時) User Initiated
⠸ Updating resources in the cloud. This may take a few minutes...

CREATE_IN_PROGRESS hostingamplifyhosting AWS::CloudFormation::Stack Sun Nov 15 2020 22:27:37 GMT+0900 (日本標準時)                            
UPDATE_IN_PROGRESS UnauthRole            AWS::IAM::Role             Sun Nov 15 2020 22:27:38 GMT+0900 (日本標準時)                            
UPDATE_IN_PROGRESS DeploymentBucket      AWS::S3::Bucket            Sun Nov 15 2020 22:27:38 GMT+0900 (日本標準時)                            
UPDATE_IN_PROGRESS AuthRole              AWS::IAM::Role             Sun Nov 15 2020 22:27:38 GMT+0900 (日本標準時)                            
CREATE_IN_PROGRESS hostingamplifyhosting AWS::CloudFormation::Stack Sun Nov 15 2020 22:27:39 GMT+0900 (日本標準時) Resource creation Initiated
⠼ Updating resources in the cloud. This may take a few minutes...

CREATE_IN_PROGRESS amplify-amplifyjsapp-dev-222121-hostingamplifyhosting-AYTGZ9EGRGD0 AWS::CloudFormation::Stack Sun Nov 15 2020 22:27:39 GMT+0900 (日本標準時) User Initiated
⠦ Updating resources in the cloud. This may take a few minutes...

CREATE_IN_PROGRESS AmplifyBranch AWS::Amplify::Branch Sun Nov 15 2020 22:27:44 GMT+0900 (日本標準時) 
⠏ Updating resources in the cloud. This may take a few minutes...

UPDATE_COMPLETE UnauthRole AWS::IAM::Role Sun Nov 15 2020 22:27:54 GMT+0900 (日本標準時) 
UPDATE_COMPLETE AuthRole   AWS::IAM::Role Sun Nov 15 2020 22:27:56 GMT+0900 (日本標準時) 
⠋ Updating resources in the cloud. This may take a few minutes...

CREATE_IN_PROGRESS AmplifyBranch AWS::Amplify::Branch Sun Nov 15 2020 22:27:56 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_COMPLETE    AmplifyBranch AWS::Amplify::Branch Sun Nov 15 2020 22:27:56 GMT+0900 (日本標準時)                            
⠸ Updating resources in the cloud. This may take a few minutes...

CREATE_COMPLETE amplify-amplifyjsapp-dev-222121-hostingamplifyhosting-AYTGZ9EGRGD0 AWS::CloudFormation::Stack Sun Nov 15 2020 22:27:57 GMT+0900 (日本標準時) 
⠙ Updating resources in the cloud. This may take a few minutes...

UPDATE_COMPLETE DeploymentBucket      AWS::S3::Bucket            Sun Nov 15 2020 22:27:58 GMT+0900 (日本標準時) 
CREATE_COMPLETE hostingamplifyhosting AWS::CloudFormation::Stack Sun Nov 15 2020 22:28:01 GMT+0900 (日本標準時) 
⠸ Updating resources in the cloud. This may take a few minutes...

UPDATE_COMPLETE_CLEANUP_IN_PROGRESS amplify-amplifyjsapp-dev-222121 AWS::CloudFormation::Stack Sun Nov 15 2020 22:28:04 GMT+0900 (日本標準時) 
UPDATE_COMPLETE                     amplify-amplifyjsapp-dev-222121 AWS::CloudFormation::Stack Sun Nov 15 2020 22:28:05 GMT+0900 (日本標準時) 
✔ All resources are updated in the cloud


Publish started for amplifyhosting

> amplify-js-app@1.0.0 build /home/osmaniax/dev/npm/amplify-js-app
> webpack

Hash: 0c17d0ba4de267f1eb4c
Version: webpack 4.44.2
Time: 255ms
Built at: 2020/11/15 22:28:39
         Asset      Size  Chunks             Chunk Names
    index.html  1.67 KiB          [emitted]  
main.bundle.js  31.1 KiB    main  [emitted]  main
Entrypoint main = main.bundle.js
[./src/app.js] 0 bytes {main} [built]
✔ Zipping artifacts completed.
✔ Deployment complete!
https://dev.doq1sshw34d2q.amplifyapp.com

これで一応、Amplifyの画面を拝むことはできました。
フルスタックだと何したら良いか分からないので、何かフレームワークを選択してみた方がいいかな、今日はここまで!!