This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Automate Building a Unique Domain Hosting Environment with AWS CDK


img



I automated constructing a singular area internet hosting atmosphere with AWS CDK πŸŽ‰

In my earlier article, “Construct a Distinctive Area Internet hosting Setting with Amazon Route 53, AWS WAF, Amazon CloudFront, and Amazon S3” and “Automate Constructing a Distinctive Area Internet hosting Setting with AWS CloudFormation,” I attempted to implement the contents of those articles with AWS CDK.

I’ve made the template accessible on GitHub, so please use it!

aws-cdk-templates-showcase



/lib/unique-domain-hosting-stack.ts

import { Stack, StackProps, RemovalPolicy, CfnOutput } from 'aws-cdk-lib';
import { Assemble } 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: Assemble, id: string, props?: StackProps) {
    tremendous(scope, id, props);
    const domainName = this.node.tryGetContext('domainName');
    const {
      accountId,
      area,
    } = new cdk.ScopedAws(this);
    const hostedZoneId = route53.HostedZone.fromLookup(this, 'HostedZoneId', {
      domainName: domainName
    });
    const certificateManagerCertificate = new acm.DnsValidatedCertificate(this, 'CertificateManagerCertificate', {
      domainName: domainName,
      hostedZone: hostedZoneId,
      area: 'us-east-1',
      validation: acm.CertificateValidation.fromDns(),
    });
    const s3Bucket = new s3.Bucket(this, 'S3Bucket', {
      bucketName: `${domainName}-${area}-${accountId}`,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      removalPolicy: RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
    });
    const cloudFrontOAI = new cloudfront.OriginAccessIdentity(this, 'CloudFrontOriginAccessIdentityy', {
      remark: 'Distinctive Area Internet hosting Setting',
    })
    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,
      certificates: 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,
      goal: 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', {
      worth: `https://${domainName}`,
    })
  }
}
Enter fullscreen mode

Exit fullscreen mode



/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: course of.env.CDK_DEFAULT_ACCOUNT,
    area: course of.env.CDK_DEFAULT_REGION
  },
});
Enter fullscreen mode

Exit fullscreen mode



cdk.json

{
  "app": "npx ts-node --prefer-ts-exts bin/unique-domain-hosting.ts",
  "watch": {
    "embody": [
      "**"
    ],
    "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": "Area Title Settings"
  }
}
Enter fullscreen mode

Exit fullscreen mode



bundle.json

{
  "title": "unique-domain-hosting",
  "model": "0.1.0",
  "bin": {
    "unique-domain-hosting": "bin/unique-domain-hosting.js"
  },
 "scripts": {
    "construct": "tsc",
    "watch": "tsc -w",
    "take a look at": "jest",
    "cdk": "cdk"
  },
  "key phrases": [],
  "creator": "Yasunori Kirimoto",
  "license": "ISC",
  "devDependencies": {
    "@sorts/jest": "^26.0.10",
    "@sorts/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"
  }
}
Enter fullscreen mode

Exit fullscreen mode



Advance Preparation

img

Execution atmosphere

  • node v16.10.0
  • npm v7.24.0



The right way to construct

  1. Deployment of recordsdata and updating of configuration recordsdata
  2. Auto-deploy distinctive area internet hosting atmosphere



Deployment of Recordsdata and Updating of Configuration Recordsdata

First, replace every file association and configuration file.

Use the “unique-domain-hosting” listing within the “aws-cdk-templates-showcase” repository or copy it to an arbitrary location.
img

Set the distinctive area title obtained from Amazon Route 53 in “cdk.json.”

"domainName": "Area Title Settings"
Enter fullscreen mode

Exit fullscreen mode

Copy the set of software recordsdata you want to deploy to the “dist” listing.
img



Auto-Deploy Distinctive Area Internet hosting Setting

Lastly, we’ll robotically deploy our distinctive area internet hosting atmosphere.

Set up bundle

npm set up
Enter fullscreen mode

Exit fullscreen mode

Execute the next command solely the primary time earlier than deploying. Additionally, run this command if you change the area.

cdk bootstrap
Enter fullscreen mode

Exit fullscreen mode

img

Deploy the undertaking.

cdk deploy
Enter fullscreen mode

Exit fullscreen mode

img

Verify that the stack has been created. You’ll be able to see that every service can also be created robotically.
img

Whenever you entry your distinctive area, you will notice the deployed WebSite.
img

Utilizing AWS CDK makes it doable to automate the development of assorted assets, resembling your distinctive area internet hosting. On this case, it was doable to create ACM in a hard and fast area, robotically generate S3 bucket insurance policies for CloudFront, and outline the appliance to be deployed within the code with a small quantity of code. Every function definition must be realized from the documentation in addition to AWS CloudFormation, however it’s a very promising device, and it’s enjoyable to construct.

I hope to automate much more sooner or later!

Associated Articles

References

AWS CDK
API Reference

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?