AWS CDK로 고유한 도메인 호스팅 환경 구축 자동화

AWS CDK로 고유한 도메인 호스팅 환경 구축을 자동화했습니다 🎉
이전 글 ""과 ""에서 이 글의 내용을 AWS CDK로 구현해 보았습니다.
GitHub에 템플릿을 올려두었으니 많이 이용해주세요!
aws-cdk-templates-showcase
/lib/unique-domain-hosting-stack.ts
import { Stack, StackProps, RemovalPolicy, CfnOutput } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as cdk from 'aws-cdk-lib';
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
import * as targets from 'aws-cdk-lib/aws-route53-targets';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';
export class UniqueDomainHostingStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const domainName = this.node.tryGetContext('domainName');
const {
accountId,
region,
} = new cdk.ScopedAws(this);
const hostedZoneId = route53.HostedZone.fromLookup(this, 'HostedZoneId', {
domainName: domainName
});
const certificateManagerCertificate = new acm.DnsValidatedCertificate(this, 'CertificateManagerCertificate', {
domainName: domainName,
hostedZone: hostedZoneId,
region: 'us-east-1',
validation: acm.CertificateValidation.fromDns(),
});
const s3Bucket = new s3.Bucket(this, 'S3Bucket', {
bucketName: `${domainName}-${region}-${accountId}`,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
const cloudFrontOAI = new cloudfront.OriginAccessIdentity(this, 'CloudFrontOriginAccessIdentityy', {
comment: 'Unique Domain Hosting Environment',
})
const cloudFrontDistribution = new cloudfront.Distribution(this, 'CloudFrontDistribution', {
domainNames: [domainName],
defaultBehavior: {
origin: new origins.S3Origin(s3Bucket, {
originAccessIdentity: cloudFrontOAI
}),
compress: true,
allowedMethods: cloudfront.AllowedMethods.ALLOW_GET_HEAD,
cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
},
errorResponses: [
{
httpStatus: 403,
responsePagePath: '/index.html',
responseHttpStatus: 200,
ttl: cdk.Duration.minutes(0),
},
{
httpStatus: 404,
responsePagePath: '/index.html',
responseHttpStatus: 200,
ttl: cdk.Duration.minutes(0),
},
],
priceClass: cloudfront.PriceClass.PRICE_CLASS_ALL,
enabled: true,
certificate: certificateManagerCertificate,
minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
httpVersion: cloudfront.HttpVersion.HTTP2,
defaultRootObject: 'index.html',
enableIpv6: true,
})
new route53.ARecord(this, 'Route53RecordSet', {
recordName: domainName,
zone: hostedZoneId,
target: route53.RecordTarget.fromAlias(
new targets.CloudFrontTarget(cloudFrontDistribution)
),
});
new s3deploy.BucketDeployment(this, 'S3BucketDeploy', {
sources: [s3deploy.Source.asset('./dist')],
destinationBucket: s3Bucket,
distribution: cloudFrontDistribution,
distributionPaths: ['/*'],
});
new CfnOutput(this, 'DeployURL', {
value: `https://${domainName}`,
})
}
}
/bin/unique-domain-hosting.ts
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { UniqueDomainHostingStack } from '../lib/unique-domain-hosting-stack';
const app = new cdk.App();
new UniqueDomainHostingStack(app, 'UniqueDomainHostingStack', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION
},
});
cdk.json
{
"app": "npx ts-node --prefer-ts-exts bin/unique-domain-hosting.ts",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
},
"context": {
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
"@aws-cdk/core:stackRelativeExports": true,
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true,
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"domainName": "Domain Name Settings"
}
}
패키지.json
{
"name": "unique-domain-hosting",
"version": "0.1.0",
"bin": {
"unique-domain-hosting": "bin/unique-domain-hosting.js"
},
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"test": "jest",
"cdk": "cdk"
},
"keywords": [],
"author": "Yasunori Kirimoto",
"license": "ISC",
"devDependencies": {
"@types/jest": "^26.0.10",
"@types/node": "10.17.27",
"jest": "^26.4.2",
"ts-jest": "^26.2.0",
"aws-cdk": "2.15.0",
"ts-node": "^9.0.0",
"typescript": "~3.9.7"
},
"dependencies": {
"aws-cdk-lib": "2.15.0",
"constructs": "^10.0.0",
"source-map-support": "^0.5.16"
}
}
사전 준비

실행 환경
구축 방법
파일 배포 및 구성 파일 업데이트
먼저 각 파일 배열 및 구성 파일을 업데이트합니다.
"aws-cdk-templates-showcase "저장소의 "unique-domain-hosting"디렉토리를 사용하거나 임의의 위치에 복사하십시오.

Amazon Route 53에서 얻은 고유 도메인 이름을 "cdk.json"에 설정합니다.
"domainName": "Domain Name Settings"
배포하려는 애플리케이션 파일 세트를 "dist"디렉터리에 복사합니다.

고유한 도메인 호스팅 환경 자동 배포
마지막으로 고유한 도메인 호스팅 환경을 자동으로 배포합니다.
패키지 설치
npm install
배포하기 전에 처음에만 다음 명령을 실행하십시오. 또한 리전을 변경할 때 이 명령을 실행하십시오.
cdk bootstrap

프로젝트를 배포합니다.
cdk deploy

스택이 생성되었는지 확인합니다. 각각의 서비스도 자동으로 생성되는 것을 확인할 수 있습니다.

고유한 도메인에 액세스하면 배포된 웹 사이트가 표시됩니다.

AWS CDK를 사용하면 고유한 도메인 호스팅과 같은 다양한 리소스의 구성을 자동화할 수 있습니다. 이 경우 고정된 지역에 ACM을 생성하고, CloudFront용 S3 버킷 정책을 자동으로 생성하고, 소량의 코드로 코드에 배포할 애플리케이션을 정의할 수 있었습니다. 각 기능 정의는 설명서와 AWS CloudFormation에서 배워야 하지만 매우 유망한 도구이며 구축하는 것이 재미있습니다.
앞으로 더 많은 것을 자동화할 수 있기를 바랍니다!
관련 기사


AWS CloudFormation으로 고유한 도메인 호스팅 환경 구축 자동화
Yasunori Kirimoto for AWS Community Builders ・ 2월 28일 ・ 4분 읽기
#aws
#cloudformation
#route53


AWS Amplify로 고유한 도메인 호스팅 환경 구축
Yasunori Kirimoto for AWS Community Builders ・ 2월 21일 ・ 7분 읽기
#amplify
#amplifyconsole
#route53
#aws


Amazon Route 53, AWS WAF, Amazon CloudFront 및 Amazon S3를 사용하여 고유한 도메인 호스팅 환경 구축
Yasunori Kirimoto for AWS Community Builders ・ 2월 7일 ・ 5분 읽기
#amazonroute53
#awswaf
#amazoncloudfront
#amazons3
참조
AWS CDK
API Reference
Reference
이 문제에 관하여(AWS CDK로 고유한 도메인 호스팅 환경 구축 자동화), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aws-builders/automate-building-a-unique-domain-hosting-environment-with-aws-cdk-1dd1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)