⚙️

【AWS】Amplify・Vue3での環境構築方法

2023/05/26に公開

はじめに

AWS Amplify と Vue.3 系を使った Web アプリケーションの構築方法を記事にします。
今回は最小単位の Vue の初期画面を Amplify で公開するところまでが対象です。

上記の内容だけですと、コマンド 2-3 叩いて終了と簡素なものになってしまいますので、どういった仕組みで Web アプリケーションとして公開されるのかなどを確認しながら試してみます。

Amplify 初学者の方はこの記事でなんとなくの仕組みをつかんでもらえたら幸いです。

この記事でわかること

この記事を読む上での前提条件

この記事で取り扱わないこと

環境情報

  • @aws-amplify/cli 12.0.0
  • npm 8.9.0
  • node 18.2.0
  • @vue/cli 5.0.8
  • vue ^3.2.13
  • git version 2.39.2
  • OS macOS ventura 13.4

GitHub

https://github.com/akkie-i/amplify-vue/tree/phase1/amplify-init

Amplify CLI のインストール

以下のコマンドを実行してください。基本はこちらの Amplify コマンドを使って環境を構築していきます。

$ npm install -g @aws-amplify/cli

以下のコマンドを実行し、バージョン情報が確認できればインストール完了です。

$ amplify --version

# 出力結果例
# 12.0.0

環境のセットアップ

Amplify CLI からユーザ作成ができますので試してみます。
既存の IAM ユーザを使用する場合はこの工程はスキップしていただいても問題ございません。

この項でやることは、Amplify の環境を構築したい対象の AWS 環境にて、IAM ユーザのアクセスキー情報作成し ~/.aws/credentials に以下の形式で登録できていることです。

[任意のプロフィール名]
aws_access_key_id=*****
aws_secret_access_key=*****

上記ができてれば方法はなんでも良いです。初めての方は後続のフローからやってみてください。

では、やってみます。以下のコマンドを実行してください。

$ amplify configure

対話形式でターミナル内で選択、入力を行います。

まずは、以下が出力され、Web 画面に AWS のログイン画面が表示されます。(セッションが残ってる場合はマネジメントコンソール画面が表示)
Amplify の環境を構築したい AWS 環境にログインして Enter⏎ を押してください。

Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

続いて、リージョンの指定を選択するように聞かれますので選択し、Enter⏎ を押します。
今回はひとまず ue-east-1 を選択しました。

Specify the AWS Region
? region:  (Use arrow keys)
❯ us-east-1
  us-east-2
  us-west-1
  us-west-2
  eu-north-1
  eu-south-1
  eu-west-1
(Move up and down to reveal more choices)

# 選択後は以下が表示
? region:  us-east-1
Follow the instructions at
https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli

続いて、IAM ユーザを作成するように促されます。Web 画面上でも IAM の作成画面が表示されます。

to complete the user creation in the AWS console
https://console.aws.amazon.com/iamv2/home#/users/create
Press Enter to continue

新規で作成する方は「IAM ユーザの作成&アクセスキー情報の取得」を参照いただき、不要な方は Enter⏎ を押して次に進んでください。

IAM ユーザの作成&アクセスキー情報の取得

ユーザー名 に任意の名前を入力し、次へ をクリック。

ポリシーを直接アタッチする を選択し、

そのまま下へスクロールし、次へ をクリック。

ユーザーの作成 をクリック。

ユーザを表示 をクリック

アクセスキーを作成 をクリック

コマンドラインインターフェース(CLI) を選択、上記のレコメンデーションを理解し、アクセスキーを作成します。 を選択し、 次へ をクリック。

アクセスキーを作成 をクリック。

.csvファイルをダウンロード をクリックし、完了 をクリックし完了。

続いて、アクセスキー情報の入力を求められます。
取得したアクセスキー CSV の項目 Access key ID をターミナルの accessKeyId の箇所にペーストし Enter⏎ を押し、CSV の項目 Secret access key をターミナルの secretAccessKey の箇所にペーストし Enter⏎ を押します。

Enter the access key of the newly created user:
? accessKeyId: *****************
? secretAccessKey: *************************************

続いて、プロフィール名の入力を求められますので任意の値を入力し、Enter⏎ を押します。
例では amplify-app-my-aws-1 としてます。

This would update/create the AWS Profile in your local machine
? Profile Name: amplify-app-my-aws-1

以下の完了メッセージを確認できます。

Successfully set up the new user.

以下のコマンドを実行し、入力した情報が反映されているかを確認します。

$ cat ~/.aws/credentials

vue プロジェクトの作成

環境のセットアップが完了しましたので、次に vue のプロジェクトを作成します。

まずは以下のコマンドを実行し、CLI をインストールしてください。

$ npm install -g @vue/cli

以下のコマンドを実行し、バージョン情報が確認できれば完了です。

$ vue --version
# 出力例
@vue/cli 5.0.8

次に以下のコマンドから空のプロジェクトを作成します。

$ vue create vue-amplify-app

vue のバージョンを指定するように入力を求められますので、3 を選択し Enter⏎ を押します。

? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)
Manually select features

# 以下が出力されれば完了
🎉 Successfully created project vue-amplify-app.
👉 Get started with the following commands:

$ cd vue-amplify-app
$ npm run serve

Amplify フルスタック・プロジェクトのセットアップ

先ほど作成した vue プロジェクト内に Amplify のフルスタック・プロジェクトを作成します。
以下のコマンドを実行してください。

$ amplify init

対話形式で選択と入力を求められます。
まずは Amplify のアプリケーション名を入力し Enter⏎ を押します。
今回は app としてます。

Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project app

# 出力結果
The following configuration will be applied:

Project information
| Name: app
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: vue
| Source Directory Path: src
| Distribution Directory Path: dist
| Build Command: npm run-script build
| Start Command: npm run-script serve

フォルダ内の構成からプロジェクトの設定値を自動で決めてくれます。
次に上記の設定内容から変更するか Y/n を入力して Enter⏎ を押します。

今回はそのままで良いので Y とします。変更したい場合は n を入力すると設定値の入力を一つ一つ求められますので入力していってください。

? Initialize the project with the above configuration? (Y/n) Y

# 出力結果
Using default provider  awscloudformation

次に AWS リソースに対しての認証方法を選択するか選択を求められます。
先ほどの「環境のセットアップ」で設定した情報を使用しますので AWS profile を選択し Enter⏎ を押します。

? Select the authentication method you want to use: (Use arrow keys)
❯ AWS profile
  AWS access keys

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

.aws/credentials 内に記載してあるプロフィール名がリストで表示されますので選択します。こちらも先ほどの「環境のセットアップ」で指定したプロフィール名を選択し、Enter⏎ を押します。

プロフィールを選択したら初期セットアップが開始されます。

? Please choose the profile you want to use
❯ amplify-app-my-aws-1

# 出力結果
Adding backend environment dev to AWS Amplify app: d2f680t44514om

Deployment completed.
Deploying root stack app [ ====================-------------------- ] 2/4
        amplify-app-dev-215222         AWS::CloudFormation::Stack     CREATE_IN_PROGRESS             Thu May 25 2023 21:52:26…
        DeploymentBucket               AWS::S3::Bucket                CREATE_IN_PROGRESS             Thu May 25 2023 21:52:29…
        AuthRole                       AWS::IAM::Role                 CREATE_COMPLETE                Thu May 25 2023 21:52:44…
        UnauthRole                     AWS::IAM::Role                 CREATE_COMPLETE                Thu May 25 2023 21:52:44…

最後に障害時に Amplify に機密性の低い情報を提供するかの選択を求められますので y/N で入力し、Enter⏎ を押します。

Help improve Amplify CLI by sharing non sensitive configurations on failures (y/N) N

# 出力結果
Deployment state saved successfully.
✔ 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 push" to deploy everything

こちらで AWS にリソースがデプロイされました。次の項で詳しくみていきます。

構築は CloudFormation で実行される

Amplify のフルスタック・プロジェクトを作成し終えると amplify フォルダが作成されます。

その中は以下の構成になっています。

.
├── #current-cloud-backend
│   ├── amplify-meta.json
│   ├── awscloudformation
│   │   └── build
│   │       └── root-cloudformation-stack.json
│   └── tags.json
├── README.md
├── backend
│   ├── amplify-meta.json
│   ├── awscloudformation
│   │   └── build
│   │       └── root-cloudformation-stack.json
│   ├── backend-config.json
│   ├── tags.json
│   └── types
│       └── amplify-dependent-resources-ref.d.ts
├── cli.json
├── hooks
│   ├── README.md
│   ├── post-push.sh.sample
│   └── pre-push.js.sample
└── team-provider-info.json

cloudformation と言った文言が見受けられますね。
ファイルからも推察できるように、デプロイは CloudFormation を元に実行されます。

AWS 上にもスタックが作成されていることが確認できます。

中身はどんなかも確認してみましょう。(長いのトグルにしてます)

cloudFormationStack
amplify/backend/awscloudformation/build/root-cloudformation-stack.json
{
  "Description": "Root Stack for AWS Amplify CLI",
  "AWSTemplateFormatVersion": "2010-09-09",
  "Parameters": {
    "DeploymentBucketName": {
      "Type": "String",
      "Default": "DeploymentBucket",
      "Description": "Name of the common deployment bucket provided by the parent stack"
    },
    "AuthRoleName": {
      "Type": "String",
      "Default": "AuthRoleName",
      "Description": "Name of the common deployment bucket provided by the parent stack"
    },
    "UnauthRoleName": {
      "Type": "String",
      "Default": "UnAuthRoleName",
      "Description": "Name of the common deployment bucket provided by the parent stack"
    }
  },
  "Outputs": {
    "Region": {
      "Description": "CloudFormation provider root stack Region",
      "Value": {
        "Ref": "AWS::Region"
      },
      "Export": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-Region"
        }
      }
    },
    "StackName": {
      "Description": "CloudFormation provider root stack ID",
      "Value": {
        "Ref": "AWS::StackName"
      },
      "Export": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-StackName"
        }
      }
    },
    "StackId": {
      "Description": "CloudFormation provider root stack name",
      "Value": {
        "Ref": "AWS::StackId"
      },
      "Export": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-StackId"
        }
      }
    },
    "AuthRoleArn": {
      "Value": {
        "Fn::GetAtt": [
          "AuthRole",
          "Arn"
        ]
      }
    },
    "UnauthRoleArn": {
      "Value": {
        "Fn::GetAtt": [
          "UnauthRole",
          "Arn"
        ]
      }
    },
    "DeploymentBucketName": {
      "Description": "CloudFormation provider root stack deployment bucket name",
      "Value": {
        "Ref": "DeploymentBucketName"
      },
      "Export": {
        "Name": {
          "Fn::Sub": "${AWS::StackName}-DeploymentBucketName"
        }
      }
    },
    "AuthRoleName": {
      "Value": {
        "Ref": "AuthRole"
      }
    },
    "UnauthRoleName": {
      "Value": {
        "Ref": "UnauthRole"
      }
    }
  },
  "Resources": {
    "DeploymentBucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": {
          "Ref": "DeploymentBucketName"
        },
        "BucketEncryption": {
          "ServerSideEncryptionConfiguration": [
            {
              "ServerSideEncryptionByDefault": {
                "SSEAlgorithm": "AES256"
              }
            }
          ]
        }
      },
      "UpdateReplacePolicy": "Retain",
      "DeletionPolicy": "Retain"
    },
    "AuthRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Sid": "",
              "Effect": "Deny",
              "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
              },
              "Action": "sts:AssumeRoleWithWebIdentity"
            }
          ]
        },
        "RoleName": {
          "Ref": "AuthRoleName"
        }
      }
    },
    "UnauthRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Sid": "",
              "Effect": "Deny",
              "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
              },
              "Action": "sts:AssumeRoleWithWebIdentity"
            }
          ]
        },
        "RoleName": {
          "Ref": "UnauthRoleName"
        }
      }
    }
  }
}

Resources を見ると S3 バケット、IAM ロール(AuthRole と UnauthRole)が作成されていることが確認できますね。

S3 はデプロイした資材が格納されている場所になります。IAM ロールは今後認証機能などを追加するときに使用されるロールになります。

それぞれ管理画面上からも作成されていることが確認できます。

IAM ロール:

バケット:

また、当然ですが Amplify のアプリケーションの構築も完了してます。

機能の追加方法

こんな感じで Amplify では amplify XXX コマンドを使用してバックエンド側の構築をサクサクと行い、開発者はフロントの開発に集中できるようになります。

詳細は別の記事で扱いますので触りだけ書くと、amplify add api を実行し API をサクッと作ったり、amplify add auth を実行し認証機能をサクッと作ったりすることが可能です。

コマンドで機能や資材を追加するごとに CloudFormation の定義ファイルが変更されていきますので、その度に amplify push を実行するとファイル定義に沿ってデプロイが行われると言った仕組みです。

amplify CLI でどう言ったコマンドがあるかは help で確認することができます。

$ amplify --help
amplify --help
The Amplify Command Line Interface (CLI) is a unified toolchain to
create, integrate, and manage the AWS cloud services for your app.

USAGE
  amplify <command> <subcommand> [flags]

COMMANDS
  init           Initialize a new Amplify project
  configure      Configure the CLI to work with your AWS profile
  push           Provisions cloud resources with the latest local changes
  pull           Fetch upstream backend changes from the cloud and updates the local environment
  env            Displays and manages environment related information for your Amplify project
  add            Adds a resource for an Amplify category in your local backend
  status         Shows the state of local resources not yet pushed to the cloud
  plugin         Configure Amplify plugins
  update         Update resource for an Amplify category in your local backend
  publish        Executes amplify push and hosts the frontend app
  remove         Removes a resource for an Amplify category in your local backend
  console        Opens the web console for the selected cloud resource
  delete         Delete the Amplify project
  upgrade        Download and install the latest version of the Amplify CLI
  import         Imports existing resources to your local backend
  override       Override Amplify-generated resources with Cloud Development Kit (CDK)
  diagnose       Capture non-sensitive Amplify backend metadata for debugging purposes
  logout         Logs out of Amplify Studio
  export         Export Amplify CLI-generated backend as a Cloud Development Kit (CDK) stack
  uninstall      Uninstall the Amplify CLI
  serve          Executes amplify push, and then test run the client-side application locally
  mock           Run mock server for testing categories locally
  codegen        Generates GraphQL statements and type annotations
  api            Enable an easy and secure solution to access backend data
  storage        Enable a mechanism for managing user content
  notifications  Configure notifications for your Amplify project
  auth           Enable sign-in, sign-up, and sign-out for your app
  geo            Configure geo resources for your Amplify project
  analytics      Add analytics resources to your Amplify project
  function       Configure function resources for your Amplify project
  hosting        Configure hosting resources for your Amplify project
  interactions   Configure interactions resources for your Amplify project
  predictions    Configure predictions resources for your Amplify project
  build          Builds all resources in the project

FLAGS
  -h | --help  Show help for a command

LEARN MORE
  Visit https://docs.amplify.aws/cli/

アプリの公開

作った Amplify のアプリケーションを Web に公開してみます。

まずは以下のコマンドでホスティングします。

$ amplify add hosting

何でホスティングするかを選択し Enter⏎ を押します。今回は最初に選択されていた Amplify Console で実行します。

? Select the plugin module to execute …  (Use arrow keys or type to filter)
❯ Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
  Amazon CloudFront and S3

次にデプロイ方式の選択です。今回はそのまま Manual deployment を選択して Enter⏎ を押します。

Choose a type (Use arrow keys)
Continuous deployment (Git-based deployments)
❯ Manual deployment
Learn more

You can now publish your app using the following command:

Command: amplify publish

ホスティングできましたので以下のコマンドでアプリケーションを実行します。

$ amplify publish

実行内容が表示されますので問題ないようでしたら Y を入力して続行します。

✔ 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? (Y/n)

✔ Deployment complete! の文言が最後に表示されれば完了です。

また、以下のコマンドで環境情報を参照でき、そこで公開された URL を確認できますのでアクセスすると vue のトップ画面が表示されることが確認できるかと思います。

$ amplify status

# 実行結果
    Current Environment: dev

┌──────────┬────────────────┬───────────┬───────────────────┐
│ Category │ Resource name  │ Operation │ Provider plugin   │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Hosting  │ amplifyhosting │ No Change │ awscloudformation │
└──────────┴────────────────┴───────────┴───────────────────┘


Amplify hosting urls:
┌──────────────┬───────────────────────────────────────────┐
│ FrontEnd Env │ Domain                                    │
├──────────────┼───────────────────────────────────────────┤
│ dev          │ https://dev.d2f680t44514om.amplifyapp.com │
└──────────────┴───────────────────────────────────────────┘

アプリを非公開にする

先ほど公開したアプリを非公開にしたい場合は以下のコマンドを実行ください。

$ amplify remove hosting

確認のプロンプトが表示されますので y/n で選択を入力し Enter⏎ を押します。
Successfully removed resource が表示されることが確認できます。

? Are you sure you want to delete the resource? This action deletes all files related to this resource from the backend directory. Yes

# 出力結果
✅ Successfully removed resource

ステータス確認の以下のコマンドを実行するとホスティングが削除されたことを確認できます。

$ amplify status

# 出力結果
    Current Environment: dev

┌──────────┬────────────────┬───────────┬───────────────────┐
│ Category │ Resource name  │ Operation │ Provider plugin   │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Hosting  │ amplifyhosting │ Delete    │ awscloudformation │
└──────────┴────────────────┴───────────┴───────────────────┘

次に内容を反映するために以下のコマンドを実行します。

$ amplify push

そのまま続けるかを Y/n で選択し Enter⏎ を押します。

✔ Successfully pulled backend environment dev from the cloud.

    Current Environment: dev

┌──────────┬────────────────┬───────────┬───────────────────┐
│ Category │ Resource name  │ Operation │ Provider plugin   │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Hosting  │ amplifyhosting │ Delete    │ awscloudformation │
└──────────┴────────────────┴───────────┴───────────────────┘
✔ Are you sure you want to continue? (Y/n) · yes

# 出力結果
Deployment completed.
Deployed root stack app [ ======================================== ] 1/1
        amplify-app-dev-12202          AWS::CloudFormation::Stack     UPDATE_COMPLETE                Fri May 26 2023 01:28:24…

Deployment state saved successfully.


Browserslist: caniuse-lite is outdated. Please run:
  npx update-browserslist-db@latest
  Why you should do it regularly: https://github.com/browserslist/update-db#readme

Deployment state saved successfully. が表示されれば完了です。先ほど公開した時の URL にアクセスすると画面が表示されなくなることが確認できます。

アプリを削除する

アプリの非公開でなく削除も確認してみます。
このコマンドを実行すると、AWS 上だけでなく、ローカルのコードから Amplify の資源が全て削除されます。

以下のコマンドを実行ください。

$ amplify delete

確認のプロンプトが表示されますので y/N で選択を入力し Enter⏎ を押します。

✔ Are you sure you want to continue? This CANNOT be undone. (This will delete all the environments of the project from the cloud and wipe out all the local files created by Amplify CLI) (y/N) · yes

# 出力結果
⠋ Deleting resources from the cloud. This will take a few minutes.
Deleting env: dev.
✔ Project deleted in the cloud.
✅ Project deleted locally.

✔ Project deleted in the cloud.✅ Project deleted locally. が表示されたことを確認できれば削除完了です。

さいごに

さいごまで読んでいただきありがとうございます。

今回は基本的な環境構築だけですので、他のフレームワークとの違いとか、ホスティングと公開をサクッとできるのも既存の PaaS などと比べてもあまり違いがわからなかったかもしれないですね。

次からは実際に機能を載せていく記事を作成する予定ですが、そこで Amplify の良いところがもっと伝えられると思ってます。

バックエンドの開発はほぼ 0 であとはフロントのアプリケーションの構築に集中するだけみたいなノリになってきます。

今後 ChatGPT とかで HTML/CSS は吐き出されるみたいな時代になってくるとも思いますし、いよいよニートになる日も近いなとしみじみ感じる次第です w

今回のサンプルは「GitHub」にもまとめているので併せてご確認ください。

間違いの指摘やリクエストなどありましたら加筆していきたので是非、ご意見をいただけたらと思います。

それではまた次の記事でお会いしましょう。

GitHubで編集を提案

Discussion