Triển khai angular web với AWS CDK

by khanhcd92
397 views
This entry is part [part not set] of 2 in the series AWS CDK

Ở phần đầu của series, mình đã giới thiệu AWS CDK là gì. Nay để hiểu rõ nó hơn mình sẽ giới thiệu cách triển khai 1 web angular với AWS CDK.

Chuẩn bị

  • Chuẩn bị sẵn account AWS
  • Cài đặt NodeJS
  • Cài đặt Typescript: npm i -g typescript
  • Cài đặt AWS CLI
  • Cấu hình AWS client: aws configure. Bạn sẽ cần nhập thông tin access key ID, secret access key và aws region. Chi tiết cấu hình bạn có tìm ở đây
  • Cài đẳt AWS CDK: npm install -g aws-cdk

Thực hiện

  • Tạo một thư mục static_web_cdk.

  • Trong thư mục này tạo 2 thư mục con, 1 cái angular-sample-web cho website và 1 cái infrastructure cho phần infra.

Build source code Angular

  • Di chuyển đến thư mục ngular-sample-web. Trong thư mục này mình sẽ download sample từ trên trang chủ Angular về để sử dung Xem chi tiết ở đây.

web1

  • Di chuyển đến thư mục infrastructure

  • Khơi tạo source code infrastructure: cdk init app --language typescript. Lệnh này sẽ gen ra sample code cho chúng ta.

web2

  • Mở file bin/infrastructure.ts, thêm stackName và uncomment phần env. Phần env này chúng sẽ sử dụng mặc định như bên dưới.
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { InfrastructureStack } from '../lib/infrastructure-stack';

const app = new cdk.App();
new InfrastructureStack(app, 'InfrastructureStack', {
  /* If you don't specify 'env', this stack will be environment-agnostic.
   * Account/Region-dependent features and context lookups will not work,
   * but a single synthesized template can be deployed anywhere. */
  stackName: 'web-static-stack',
  /* Uncomment the next line to specialize this stack for the AWS Account
   * and Region that are implied by the current CLI configuration. */
  env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },

  /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
});
  • Bây giờ mở file /lib/infrastructure-stack.ts nơi chúng ta sẽ khai báo các dịch vụ của stack.

Khai báo các thành phần của Stack

Để triển khai Angular web static mình sử dụng các dịch vụ CloudFront và S3. CloudFront sẽ access vào private S3 thông qua OAI (Origin Access Identity). Vậy thì Stack cần phải code những gì mọi người theo dõi bên dưới nhé.

  • Cài đặt thư viện @aws-cdk/aws-s3 để sử dụng được dịch vụ s3.
  • Cài đặt thư viện @aws-cdk/aws-cloudfront để sử dụng dịch vụ cloudfront.
  • Cài đặt thư viện @aws-cdk/aws-iam để sử dụng khai báo Policy cho S3
  • Trong file lib/infrastructure-stack.ts, chúng ta sẽ cần import các thư viện phía trên vào. Sau đó ở sau ta sẽ cần khai báo các dịch vụ bên duới dòng comment //The code that defines your stack goes here:
import * as cdk from '@aws-cdk/core';
import { BlockPublicAccess, Bucket, BucketEncryption } from '@aws-cdk/aws-s3';
import { CloudFrontWebDistribution, OriginAccessIdentity } from '@aws-cdk/aws-cloudfront';
import { PolicyStatement } from '@aws-cdk/aws-iam';

export class InfrastructureStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here
    // Khai báo S3
    const myBucket = new Bucket(this, "static-website-bucket", {
      bucketName: 'static-web-sample-s3',
      versioned: true,
      encryption: BucketEncryption.S3_MANAGED,
      blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
      websiteIndexDocument: "index.html"
    });

    // Khai báo OAI
    const oia = new OriginAccessIdentity(this, 'OIA', {
      comment: "Created by CDK"
    });

    // Khai báo Policy cho S3
    const policyStatement = new PolicyStatement();
    policyStatement.addActions('s3:GetObject');
    policyStatement.addResources(`${myBucket.bucketArn}/*`);
    policyStatement.addCanonicalUserPrincipal(oia.cloudFrontOriginAccessIdentityS3CanonicalUserId);
    myBucket.addToResourcePolicy(policyStatement);

    // Khai báo CloudFront
    new CloudFrontWebDistribution(this, 'static-website-cf', {
      originConfigs: [
        {
          s3OriginSource: {
            s3BucketSource: myBucket,
            originAccessIdentity: oia
          },
          behaviors: [
            { isDefaultBehavior: true }
          ]
        }
      ]
    });

    // Output giá trị DNS của CloudFront
    new CfnOutput(this, 'CloudFrontDNS', {
      value: cfWebStatic.distributionDomainName
    })
  }
}

  • Tiêp theo chúng ta sẽ phần khai báo deploy. Bạn sẽ cần cài thư viện @aws-cdk/aws-s3-deployment và thêm import * as s3Deployment from '@aws-cdk/aws-s3-deployment' vào file stack và khai báo deploy như bên dưới:
const deployment = new s3Deployment.BucketDeployment(this, "deployStaticWebsite", {
      sources: [s3Deployment.Source.asset("../angular-sample-web/dist")],
      destinationBucket: myBucket,
    });
  • Thuộc tính s3Deployment.Source.asset("../angular-sample-web/dist") là nơi mọi người sẽ cần update tới đúng vị trị source code mình đang dùng.

Triển khai

Bây giờ chúng ta sẽ cần triển khai stack này tới AWS:

  • Di chuyển đến thư mục angular-sample-web

  • Cài đặt các thư viện npm i

  • Build Angular app ng build --prod. Lúc này bundle source code sẽ được gen ra trong thư mục dist

  • Sau khi build xong Angular app thì di chuyển đến thư mục infrastructure

  • Trên cửa sổ command gõ lệnh: cdk boostrap. Thư mục cdk.out sẽ được tạo ra. Nó sẽ bao gồm code phần website và infrastructure template.

The first time you deploy an AWS CDK app into an environment (account/region), you’ll need to install a “bootstrap stack”. This stack includes resources that are needed for the toolkit’s operation. For example, the stack includes an S3 bucket that is used to store templates and assets during the deployment process.

  • Chạy lệnh cdk synth. Nó sẽ tổng hợp lại CloudFormation template cho stack.
  • Chạy lệnh cdk deploy
  • Nhập y để tiếp tục triển khai
  • Sau khi đã hoàn thành, chúng ta tới console của dịch vụ CloudFormation. Chúng ta sẽ thấy có 2 stack được tạo ra là CDKToolkit và web-static-stack

web4

  • Bây giờ vào tiếp stack web-static-stack để lấy link web.

web4

  • Click vào link CloudFrontDNS trên tab Output của màn hình stack. Bạn sẽ thấy kết quả như bên dưới.

web5

NOTE:

  • Khi bạn không dùng nữa thì có thể chạy lệnh cdk destroy để xoá stack.

  • Ví dụ bên trên là dùng cài đặt AWS client với giá trị default. Khi bạn đã thiết lập profile cho AWS thì tham khảo các câu lệnh để chạy cdk bên dưới đây nhé.

    cdk boostrap --profile profile_name
    cdk synth --profile profile_name
    cdk deploy --profile profile_name
    cdk destroy --profile profile_name
    

Bạn có thể tham khao code ở Github

Tôi hy vọng nó sẽ có ích. Bạn cũng có thể thay thế Angular với ReactJS hoặc VueJS. Xin vui lòng cho tôi biết phản hồi của bạn.

Series Navigation

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like