Amplify + Vue.js で簡単にサーバーレスPWAを構築するためのリポジトリです。
Chrome, Cloud9, GitHubを使う想定です。
なお、AWSのアカウント管理や、Cloud9などの環境設定は最低限のものになります。
したがって、実際の運用に際しては、よりセキュアな設定を別途行う事を推奨します。
参考:
https://note.com/bnctake
また、詳細の情報はAWS Amplifyの公式ページをご参照ください。
AWS Amplify:
https://aws-amplify.github.io/
以下、Cloud9環境をChromeにて表示した状態の想定で構築の手順を記します。
必要コードを転用するため、このリポジトリを環境にクローンします。
git clone https://github.com/matsuihidetoshi/vueamplifydev.git
今回のアプリケーションの構築のために、Vue.jsのプロジェクトを容易に作成できるVue CLIと
Amplifyによってアプリケーションのフロントエンド・バックエンドをコマンドで容易に構築できるAmplify CLIの
二つのCLIが必要なので、そのインストールを実施します。
npm i -g @vue/cli
npm i -g @aws-amplify/cli
Vue CLIを使って、必要な設定を行いながらVue.jsプロジェクトを作成していきます。
notesという名前でプロジェクトを作成
vue create notes
Manually select featuresを選択しEnter
Vue CLI v4.1.2
? Please pick a preset:
default (babel, eslint)
❯ Manually select features
下記の通り、Babel, Progressive Web App (PWA) Support, Router, Vuex, Linter / Formatterを選択
? Check the features needed for your project:
◉ Babel
◯ TypeScript
◉ Progressive Web App (PWA) Support
◉ Router
❯◉ Vuex
◯ CSS Pre-processors
◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
yを入力しEnter
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) y
デフォルトのESLint with error prevention onlyを選択しEnter
? Pick a linter / formatter config: (Use arrow keys)
❯ ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
デフォルトのLint on saveを選択しEnter
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Lint on save
◯ Lint and fix on commit
デフォルトのIn dedicated config filesを選択しEnter
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files
In package.json
任意だが、今回はnを入力しEnter
? Save this as a preset for future projects? (y/N) n
このままでは、Cloud9の仕組み上、起動した開発環境のサーバーをうまくプレビューできないため
設定を追加します。
- vueamplifydev/vue.config.js
を
- notes/vue.config.js
となる様にコピー
開発環境のローカルサーバーを起動してプレビューし、問題なくVue.jsプロジェクトが
立ち上がることを確認します。
cd notes
npm run serve
Cloud9画面の上部のPreview→Preview Running Applicationを、Vue.jsのデフォルト画面が表示されればOK
*そのままサーバーは起動したまま、別ターミナルを開き、notesディレクトリに移動して以降の作業を実施
Amplify CLIを使用して各種機能追加に伴うコードの生成やAWSリソースの追加を自動で行うことができます。
AWSのリソースの操作をCLIから行える様にするために、専用のIAMユーザーの追加と認証情報の設定を行う必要があります。
amplify configure
Follow these steps to set up access to your AWS account:
Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue
下記の通りap-northeast-1を選択しEnter
Specify the AWS Region
? region:
eu-west-1
eu-west-2
eu-central-1
❯ ap-northeast-1
ap-northeast-2
ap-southeast-1
ap-southeast-2
(Move up and down to reveal more choices)
任意だが今回はデフォルトのユーザー名を使用(そのままEnter)
Specify the username of the new IAM user:
? user name: (amplify-xxxxx)
下記の様に案内されるURLを開く
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-xxxxx&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue
ブラウザの別タブでAWSマネジメントコンソールのIAMユーザー作成画面が開くので
ユーザー詳細の設定→アクセス許可の設定→タグの追加 (オプション)→確認まで全てデフォルトのまま進み
「ユーザーの作成」ボタンを押下
IAMユーザーセキュリティ認証情報のページが開くので、「.csvのダウンロード」ボタンを押下
*このあとすぐダウンロードしたファイル内の情報を使用するため、ブラウザ下部のダウンロードファイルの表示を
開いたままにするなどし、すぐに開ける様にしておく
Cloud9環境の画面に戻る
下記の表示の状態で、Enter
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=amplify-xxxxx&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue
先ほどダウンロードした.csvファイルをブラウザ下部から開き、Access key IDをコピー
ターミナルに戻り、ペーストしEnter
Enter the access key of the newly created user:
? accessKeyId: (<YOUR_ACCESS_KEY_ID>)
同じく.csvファイルよりSecret access keyをコピー
ターミナルに戻り、ペーストしEnter
? secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
デフォルトのままEnter
Profile Name: (default)
*ここで、AWS managed temporary credentialsというダイアログが立ち上がり
Could not update credentialsと表示されるが、「Fource update」ボタンを押下すればOK
ターミナルは下記のメッセージが出力されていればOK
Successfully set up the new user.
Vue.jsプロジェクトをAmplifyプロジェクトとして初期化することで、各種機能追加に伴うコードの自動生成と
プロジェクトのフロントエンドに紐付いたバックエンドの役割を担う各種AWSリソースの構築を
CLIから実行することができる様になります。
この操作が完了すると、同時にAmplifyバックエンドの素体の様なものがCloudFormationによりクラウド上に作成されます。
amplify init
デフォルト(Vue.jsプロジェクトとしての名前:notes)のままEnter
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project (notes)
任意だが、今回はdefaultと入力しEnter
? Enter a name for the environment default
Noneを選択しEnter
? Choose your default editor:
Visual Studio Code
Atom Editor
Sublime Text
IntelliJ IDEA
Vim (via Terminal, Mac OS only)
Emacs (via Terminal, Mac OS only)
❯ None
javascriptを選択しEnter
? Choose the type of app that you're building (Use arrow keys)
android
ios
❯ javascript
vueを選択しEnter
? What javascript framework are you using (Use arrow keys)
angular
ember
ionic
react
react-native
❯ vue
none
デフォルト(src)のままEnter
? Source Directory Path: (src)
デフォルト(dist)のままEnter
? Distribution Directory Path: (dist)
npm run buildと入力しEnter
? Build Command: npm run build
npm run serveと入力しEnter
? Start Command: npm run serve
yを入力しEnter
Using default provider awscloudformation
For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html
? Do you want to use an AWS profile? (Y/n) y
先ほど作成したプロファイル(default)を選択しEnter
? Please choose the profile you want to use (Use arrow keys)
❯ default
下記の様なメッセージが表示されれば成功
✔ 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を導入しているため、コマンドを実行することで最低限必要なフロントエンドのコードの生成と
バックエンドの認証基盤(Lambda + Cognito)の構築を数ステップで完了できます。
amplify add auth
Default configurationを選択しEnter
Do you want to use the default authentication and security configuration? (Us
e arrow keys)
❯ Default configuration
Default configuration with Social Provider (Federation)
Manual configuration
I want to learn more.
Emailを選択しEnter
Warning: you will not be able to edit these selections.
How do you want users to be able to sign in?
Username
❯ Email
Phone Number
Email and Phone Number
I want to learn more.
No, I am done.を選択しEnter
Do you want to configure advanced settings? (Use arrow keys)
❯ No, I am done.
Yes, I want to make some additional changes.
アプリケーションに基本的なAPIを追加します。
認証機能と同様、コマンドで簡単にフロントエンド側のコードと、CRUDが可能なAPIバックエンド
(AppSync + DynamoDB)を構築できます。
また、GraphQLのSubscriptionにより、Websocketを使ったイベントドリブンなフロントエンドへの
リアルタイムデータ更新を実現します。
amplify add api
GraphQLを選択しEnter
? Please select from one of the below mentioned services: (Use arrow keys)
❯ GraphQL
REST
デフォルトのアプリケーション名(notes)のままEnter
? Provide API name: (notes)
Amazon Cognito User Poolを選択しEnter
? Choose the default authorization type for the API
API key
❯ Amazon Cognito User Pool
IAM
OpenID Connect
No, I am done.を選択しEnter
? Do you want to configure advanced settings for the GraphQL API (Use arrow ke
ys)
❯ No, I am done.
Yes, I want to make some additional changes.
nを入力しEnter
? Do you have an annotated GraphQL schema? (y/N) n
yを入力しEnter
? Do you want a guided schema creation? (Y/n) y
Objects with fine-grained access control
(e.g., a project management app with owner-based authorization)を選択しEnter
? What best describes your project:
Single object with fields (e.g., “Todo” with ID, name, description)
One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
❯ Objects with fine-grained access control (e.g., a project management app
with owner-based authorization)
yを入力しEnter
? Do you want to edit the schema now? (Y/n) y
下記の様なメッセージが表示されればOK
GraphQL schema compiled successfully.
Edit your schema at /home/ec2-user/environment/notes/amplify/backend/api/notes/schema.graphql or place .graphql files in a directory at /home/ec2-user/environment/notes/amplify/backend/api/notes/schema
Successfully added resource notes locally
Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud
下記の通り、/notes/amplify/backend/api/notes/schema.graphqlのファイルを編集
type Task
@model
@auth(rules: [
{allow: groups, groups: ["Managers"], queries: null, mutations: [create, update, delete]},
{allow: groups, groups: ["Employees"], queries: [get, list], mutations: null}
])
{
id: ID!
title: String!
description: String
status: String
}
type PrivateNote
@model
@auth(rules: [{allow: owner}])
{
id: ID!
content: String!
updatedAt: String #この1行のみ追加
}
現状では、バックエンドの構築と連携を実現するのに最低限必要なローカル環境のコードを自動生成しただけでした。
ここでは、生成されたコードに基づき、実際にバックエンド環境をAWSクラウド上に構築していきます。
amplify push
yを入力しEnter
Scanning for plugins...
Plugin scan successful
✔ Successfully pulled backend environment default from the cloud.
Current Environment: default
| Category | Resource name | Operation | Provider plugin |
| -------- | ------------- | --------- | ----------------- |
| Auth | notes694e6855 | Create | awscloudformation |
| Api | notes | Create | awscloudformation |
? Are you sure you want to continue? (Y/n) y
yを入力しEnter
GraphQL schema compiled successfully.
Edit your schema at /home/ec2-user/environment/notes/amplify/backend/api/notes/schema.graphql or place .graphql files in a directory at /home/ec2-user/environment/notes/amplify/backend/api/notes/schema
? Do you want to generate code for your newly created GraphQL API (Y/n) y
javascriptを選択しEnter
? Choose the code generation language target (Use arrow keys)
❯ javascript
typescript
flow
デフォルト(src/graphql/**/*.js)のままEnter
? Enter the file name pattern of graphql queries, mutations and subscriptions (src/
graphql/**/*.js)
yを入力しEnter
? Do you want to generate/update all possible GraphQL operations - queries, mutatio
ns and subscriptions (Y/n) y
デフォルト(2)のままEnter
? Enter maximum statement depth [increase from default if your schema is deeply nested] (2)
下記の様なメッセージが表示されればOK
✔ Generated GraphQL operations successfully and saved at src/graphql
✔ All resources are updated in the cloud
GraphQL endpoint: https://xxxxxxxxxxxxxxxxxxxxxxxxxx.appsync-api.ap-northeast-1.amazonaws.com/graphql
ec2-user:~/environment/notes (master)
ここまでで、
- 認証
- API
という二つの機能の最低限のコードと、バックエンドの環境が生成されました。
ここから、フロントエンドで実際に機能するコードを作成していきます。
今回は、すでにこのリポジトリにコードがあるのでそれをコピーしていきます。
npm i aws-amplify aws-amplify-vue lodash
ログイン画面を日本語メッセージにするための設定を記述したファイルです
- vueamplifydev/src/localize.js
を
- notes/src/localize.js
となる様にコピー
認証機能を提供するコンポーネントです
- vueamplifydev/src/components/SignIn.vue
を
- notes/src/components/SignIn.vue
となる様にコピー
今回の主要な機能であるメモ機能を提供するコンポーネントです
- vueamplifydev/src/components/PrivateNote.vue
を
- notes/src/components/PrivateNote.vue
となる様にコピー
アプリケーションのエントリーポイントになるファイルです。
Amplify関連のパッケージを導入するために記述を追加します。
- vueamplifydev/src/main.js
の内容を
- notes/src/main.js
に上書き
ルーティングの設定を記述するファイルです。
ログイン状態を管理してページのアクセス制御をします。
- vueamplifydev/src/router/index.js
の内容を
- notes/src/router/index.js
に上書き
アプリケーションの共通レイアウトのコンポーネントです。
各ページへのナビゲーションを追加します。
- vueamplifydev/src/App.vue
の内容を
- notes/src/App.vue
に上書き
すでにアプリケーションがローカルで起動している状態だったら、プレビューしてみてください。
起動していなければ、別ターミナルを開いて、
npm run serve
を実行してアプリケーションを起動し、プレビューしてみてください。
しかし、このままでは登録・メール認証・ログインまではできても、投稿したメモが表示されないはずです。
コピーしてきたコードでは、メモ投稿時に必要なアプリケーション固有のユーザー情報を取得するためのキーが違うためです。
まず、プレビューしている画面の右上のボタンをクリックして、Chromeの新規タブでプレビューしてください。
それから、デベロッパーツール(検証モード)をF12キーなどで開いてください。
デベロッパーツールの上部に、Elements
Console
などが並んでいますが、その右の>>
を押して、Application
を選択してください。
開いたApplication
ウインドウの左側に、Storage
→Local Storage
という項目があるかと思います。
そちらを展開し、https://xxxxxxxx.....
という項目をクリックしてください。
そうすると、Key
とValue
の一覧表示がされると思います。
Key
の内、CognitoIdentityProvider.xxxx.xxxx.LastAuthUser
というものがありますので、それを文字列クリップボードにコピーしてください。
Value
の値ではなく、Key
の値自体を選択しコピーしてください。
- vueamplifydev/src/components/PrivateNote.vue
を開いてください。
32行目の、CognitoIdentityProvider.xxxx.xxxx.LastAuthUser
を、先ほどコピーしたものに書き換えてファイルを保存してください。
これで、再度プレビューしてみると、正しくメモを投稿でき、リアルタイムに表示が更新されると思います。
ここまでで、
-
バックエンドの本番環境
-
フロントエンドのコード
が完成しました。あとは、フロントエンドの本番環境のホスティングができれば完成です。
まず、今までの変更をGitでコミットしていきます。
git add .
git commit -m 'built application'
その後、GitHubにログインしてください。
その後、上部ナビゲーションバー右上の+
をクリックし、New repository
をクリックしてください。
Repository name
に、notes
と入力し、それ以外はデフォルトのままCreate repository
をクリックしてください。
そのあとリダイレクトした画面で…or push an existing repository from the command line
という項目があります。
その内容をコピーし、ターミナルでプロジェクトフォルダにて実行してください。
git remote add origin https://github.com/ユーザー名/notes.git
git push -u origin master
下記のようにユーザー名、パスワードを求められるので、GitHubのユーザー名
パスワード
を入力してください。
Username for 'https://github.com/matsuihidetoshi/notes-final.git':ユーザー名
Password for 'https://[email protected]/matsuihidetoshi/notes-final.git':パスワード
これで、GitHubにコードがプッシュされ、デプロイの準備ができました。
通常、Webページをホスティングするには、サーバー構築・ネットワーク設定・ミドルウェアのインストール及び設定等が必要ですが、
Amplifyコンソールを使用するとWebインターフェースから少ないステップで簡単にデプロイできます。
まず、AWSマネジメントコンソールから、Amplify
を検索し、選択します。
Amplifyコンソールが開きますが、すでにnotes
というアプリケーションの項目が作成されているはずですので、それをクリックしてください。
フロントエンドのコードとして、どのGitリポジトリを参照するかの選択するかの画面が表示されますので、GitHub
を選択し、Connect branch
をクリックしてください。
GitHubの認証ページが開きますので、ユーザー名
パスワード
を入力してログインしてください。
OAuthによるアクセス許可の画面が表示されますので、Authorize xxxx
をクリックしてください。
GitHub 認証が成功しました。
と表示されます。
下部のリポジトリ
にて、notes
を選択し、ブランチはmaster
を選択し、次へ
をクリックしてください。
ビルド設定の構成
画面が開くので、Select a backend environment
でdefault
を選択してください。
Select an existing service role or create a new one so Amplify Console may access your resources.
という項目で、
Create new role
をクリックしてください。
ロールの作成
画面が表示されますので、デフォルトのまま次のステップ: アクセス権限
をクリックしてください。
次の画面でAttached アクセス権限ポリシー
という項目などが表示されますが、こちらもデフォルトのまま次のステップ: タグ
をクリックしてください。
次の画面でタグの追加(オプション)
という項目が表示されますが、こちらもデフォルトのまま次のステップ: 確認
をクリックしてください。
確認画面が開きますが、そのままロールの作成
をクリックしてください。
画面が遷移したら、そのページは閉じてしまって構いません。
先ほど開いていたAmplifyコンソールに戻り、
Select an existing service role or create a new one so Amplify Console may access your resources.
の項目のプルダウンの横の🔄マークをクリックし、
先ほど作成したamplifyconsole-backend-role
を選択してください。
その後、次へ
をクリックしてください。
確認
画面が表示されますが、保存してデプロイ
をクリックしてください。
ここから少し時間がかかりますが(10分ほど)、デプロイのフローが終わるまでお待ちください。
デプロイが完了すると、ドメイン
という項目ができていますので、そちらのリンクをクリックすると、アプリケーションが開きます。
以上で終了です。お疲れ様でした!