Amplify with Angularに入門してみた

2021.04.23

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは!DA(データアナリティクス)事業本部 インテグレーション部の大高です。

以前に下記のセッションを見て「AmplifyAppSyncを試してみたい!」と思いつつ試せていないまま、はや半年以上過ぎておりました。

が、最近チーム内の新プロダクト開発でもAppSyncの利用があったりして「改めて勉強したい!」という気持ちが強くなってきたので、今回実際にAmplifyとAngularを組み合わせて試してみることにしました。

前提

この環境は以下がインストール・設定済みの環境となります。

  • nodenv
  • yarn

また、aws cliを導入しており、利用するAWSアカウントに対するプロファイル設定も実施してあります。

最終的なゴールと今回のゴールについて

最終的なゴールとしては、ng newコマンドで作成出来る「Angularのテンプレートプロジェクトを、認証画面を備えつつAWS上でホスティングすること」にします。また、AppSyncも触りたいので、併せて簡単なAPIコールも含めます。

今回のゴールは「AngularとAmplifyの初期設定まで」とし、設定後に色々追加をしていきたいです。

準備

では早速準備をしていきましょう。

作業用ディレクトリの準備

まずはディレクトリを作成します。今回Nodeのバージョンは14.16.0を利用します。

$ mkdir amplify-angular-sample
$ cd amplify-angular-sample
$ nodenv local 14.16.0

Angular CLIのインストール

次に、Angular CLIをインストールしておきます。インストールするバージョンは最新版(latest)とします。

$ yarn global add @angular/cli@latest 
$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 11.2.10
Node: 14.16.0
OS: darwin x64

Angular: 
... 
Ivy Workspace: 

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1102.10 (cli-only)
@angular-devkit/core         11.2.10 (cli-only)
@angular-devkit/schematics   11.2.10 (cli-only)
@schematics/angular          11.2.10 (cli-only)
@schematics/update           0.1102.10 (cli-only)

Amplify CLIのインストール

続けてAmplify CLIのインストールをすすめます。今回は以下のドキュメントを参考に進めます。

$ yarn global add @aws-amplify/cli

この後に、ドキュメントにはamplify configureのステップが記載されていますが、今回は既存のAWSプロファイルを利用したいです。 以下の記事によるとamplify initの時点でプロファイルの指定が可能のようですので、設定はスキップします。

プロファイルについては、amplifyというプロファイルを事前に用意しておきます。

~/.aws/profile

[profile amplify]
region = ap-northeast-1
output = json

~/.aws/credentials

[amplify]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Angularプロジェクトの作成とデプロイ

では、ここからAngularプロジェクトの作成とデプロイを試してみます。

Angularプロジェクトの作成

ng newコマンドで雛形のプロジェクトを作成します。

$ ng new hello-amplify-angular
? Do you want to enforce stricter type checking and stricter bundle budgets in the workspace?
  This setting helps improve maintainability and catch bugs ahead of time.
  For more information, see https://angular.io/strict Yes
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
CREATE hello-amplify-angular/README.md (1029 bytes)
(略)
✔ Packages installed successfully.
    Successfully initialized git.

これで最低限のアプリケーションができました。

Amplifyの初期化処理

アプリケーションができたら、フォルダに移動してamplify initで初期化処理を行います。

基本的にはデフォルトで提案されるものを選択していきます。

amplifyのプロジェクト名はそのままhelloamplifyangularとし、各種設定についてもデフォルトで最適な値が提案されるので、そのまま進めます。また、ここで認証についても聞かれるので、事前に用意してあるAWSプロファイルのamplifyを指定して初期化処理を行います。

プロジェクト名はhello-amplify-angularとしたかったのですが、ハイフンを含めることができなかったので、本来であれば開発コード名などの、もうちょっと格好いい名前をつけると良さそうです。

$ cd hello-amplify-angular/
$ amplify init
Initializing new Amplify CLI version...
Done initializing new version.
Scanning for plugins...
Plugin scan successful
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project helloamplifyangular
The following configuration will be applied:

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

? Initialize the project with the above configuration? Yes
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS profile

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

? Please choose the profile you want to use amplify
Adding backend environment dev to AWS Amplify Console app: d295szw0luk1wb
⠇ Initializing project in the cloud...

CREATE_IN_PROGRESS amplify-helloamplifyangular-dev-115511 AWS::CloudFormation::Stack Fri Apr 23 2021 11:55:15 GMT+0900 (日本標準時) User Initiated
CREATE_IN_PROGRESS AuthRole                               AWS::IAM::Role             Fri Apr 23 2021 11:55:20 GMT+0900 (日本標準時)               
CREATE_IN_PROGRESS DeploymentBucket                       AWS::S3::Bucket            Fri Apr 23 2021 11:55:20 GMT+0900 (日本標準時)               
CREATE_IN_PROGRESS UnauthRole                             AWS::IAM::Role             Fri Apr 23 2021 11:55:20 GMT+0900 (日本標準時)               
⠇ Initializing project in the cloud...

CREATE_IN_PROGRESS AuthRole         AWS::IAM::Role  Fri Apr 23 2021 11:55:21 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS UnauthRole       AWS::IAM::Role  Fri Apr 23 2021 11:55:21 GMT+0900 (日本標準時) Resource creation Initiated
CREATE_IN_PROGRESS DeploymentBucket AWS::S3::Bucket Fri Apr 23 2021 11:55:21 GMT+0900 (日本標準時) Resource creation Initiated
⠇ Initializing project in the cloud...

CREATE_COMPLETE UnauthRole AWS::IAM::Role Fri Apr 23 2021 11:55:39 GMT+0900 (日本標準時) 
⠇ Initializing project in the cloud...

CREATE_COMPLETE AuthRole         AWS::IAM::Role  Fri Apr 23 2021 11:55:40 GMT+0900 (日本標準時) 
CREATE_COMPLETE DeploymentBucket AWS::S3::Bucket Fri Apr 23 2021 11:55:42 GMT+0900 (日本標準時) 
⠇ Initializing project in the cloud...

CREATE_COMPLETE amplify-helloamplifyangular-dev-115511 AWS::CloudFormation::Stack Fri Apr 23 2021 11:55:45 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

初期化処理ができました!実際にAWS上では何が行われたのか、AWSの管理コンソールで確認してみます。

CloudFormationのテンプレートが作成され、IAMロールが2つとS3バケットが1つ作成されています。

IAMロールは、どちらも以下のような「信頼関係」とタグが設定されたロールでした。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Deny",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity"
    }
  ]
}

S3バケットには、以下のように「#current-cloud-backend.zip」と「amplify-meta.json」が配置されていました。

また、まだ空っぽの状態ですがAmplifyのコンソール画面に、新しくアプリケーションが作成されていました。

今回は、一旦ここまででゴールです!

まとめ

以上、Amplify with Angularに入門してみました。

初期設定までは、サクサクとできて良い感じですね。また、初期化時にamplify cliによって、自動的に適切な設定がサジェストされるのがとても良いと思いました。例えば、私はVS Codeを利用しているのですが、これも自動検出されており、プロジェクトもAngularであることを検出してくれたりと、とても助かります。

今度は、実際にアプリケーションをGit上にPushしてデプロイし、ブラウザで表示できるところまで試してみたいと思います。

どなたかのお役に立てば幸いです。それでは!