【Python】Angularに入門したのでCDKでAWSにデプロイまでやってみる
もくじ
久々の更新です❗
最近Angularに入門したので、せっかくなのでAngularをcdkでデプロイしてみます👍
ざっくりこんなイメージです
前提
- CDK導入済み
- Angular導入済み
では 作っていきましょう👻
今回はゼロから実装していきます
プロジェクトのディレクトリ作成
プロジェクト用のdirectoryを作って移動します
$ mkdir cdk-angular-template && cd $_
cdk-angular-template
はプロジェクト名なので 各自ご自由に! です👍
CDKの準備
一旦CDKのベースを用意します
# sampleを作成
$ cdk init sample-app --language python
# 不要なファイル類を削除
$ rm -rf tests cdk_angular_template source.bat README.md setup.py requirements.txt
# `requirements.txt`を作ってインストール
$ echo "aws-cdk.core==1.91.0">requirements.txt
$ source .venv/bin/activate
$ pip install -r requirements.txt
Angularの準備
お次はAngular
# プロジェクトを作る
$ ng new cdk-angular-template
# 対話形式の回答はお好みで👍(下記はsample)
? 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? Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
AngularにHello world
を表示させてみます
初期に下記のファイルに書いてあったコードを全て消して1行追加
{{ hello }}
コンポーネントに変数追加
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
hello = 'Hello World' // <- コレ
title = 'cdk-angular-template';
}
Angularをビルドします
$ cd cdk-angular-template
$ npm install
$ ng build
成功するとcdk-angular-template/dist/
配下にプロジェクトができあがりますのでコレをS3に渡せばOKです👍
CDKの修正
S3バケットの用意と、バケットにファイルを同期させるのでrequirements.txt
に下記2行追加します
aws-cdk.core==1.91.0
aws-cdk.aws-s3==1.91.0 # 追加
aws-cdk.aws-s3-deployment==1.91.0 # 追加
続いてapp.py
にバケット作成とディレクトリを同期させるStackを実装します
import os
from aws_cdk import core
from aws_cdk.aws_s3 import Bucket
from aws_cdk.aws_s3_deployment import BucketDeployment, Source
class CdkAngularTemplateStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
bucket = Bucket(
self,
"CdkAngularTemplateBucket",
website_index_document="index.html",
public_read_access=True,
removal_policy=core.RemovalPolicy.DESTROY, # Stack削除と同時にバケットを削除する
)
BucketDeployment(
self,
"CdkAngularTemplateBucketDeployment",
sources=[Source.asset( "cdk-angular-template/dist/cdk-angular-template")],
destination_bucket=bucket
)
app = core.App()
env = core.Environment(account=os.getenv("CDK_DEFAULT_ACCOUNT"), region="us-east-1")
CdkAngularTemplateStack(app, "cdk-angular-template", env=env)
app.synth()
デプロイ🚀
$ cdk deploy
動作確認
ちょっとコマンドでendpointを取得する方法が分からなかったので、AWSのコンソールから今回デプロイしたバケットを開き、プロパティタブの下のほうにある 静的ウェブサイトホスティング のURLをクリックします
無事動いていることが確認できました❗
デストロイ
$ cdk destroy
まとめ
今回はAngularをCDKを使ってデプロイして、ブラウザで動作確認をしてみました!
以上です。お疲れさまでした❗