コンテンツにスキップ

最後の仕上げ

独自ドメインからのアクセスのみに限定する

これまでの設定で、WordPressへアクセスする宛先が複数出てきました。 最終的にはCloudFrontに設定した独自ドメイン以外からのアクセスを以下のルールで防ぎます。

No. AWSサービス 宛先 アクセス可否ルール
1 EC2 パブリックIPアドレス ブロック
2 EC2 AWS生成ドメイン ブロック
3 ELB AWS生成ドメイン CloudFrontの独自ドメインにリダイレクト
4 ELB 独自ドメイン CloudFrontの独自ドメインにリダイレクト
5 CloudFront AWS生成ドメイン CloudFrontの独自ドメインにリダイレクト
6 CloudFront 独自ドメイン アクセス許可
  1. EC2への直接アクセスをブロック(No.1,2)

    EC2のセキュリティグループで許可しない(=禁止する)

    wordpress-cdk/lib/wordpress-cdk-stack.ts
    // ec2_sg.addIngressRule(aws_ec2.Peer.anyIpv4(), aws_ec2.Port.tcp(80))
    
  2. CloudFront独自ドメインにリダイレクト(No.3,4,5)

    ELBのリスナールールを設定
    HOSTヘッダーが一致したらリダイレクト

    wordpress-cdk/lib/wordpress-cdk-stack.ts
    const listener_http = elb.addListener('Listener_http', {
      port: 80,
      open: true,
      defaultTargetGroups: [elb_targetgroup],
    })
    
    const listener_https = elb.addListener('Listener_https', {
      port: 443,
      open: true,
      certificates: [elb_cert],
      defaultTargetGroups: [elb_targetgroup],
    })
    
    new aws_elasticloadbalancingv2.ApplicationListenerRule(this, 'listener_http_rule', {
      listener: listener_http,
      priority: 10,
      conditions: [
        aws_elasticloadbalancingv2.ListenerCondition.hostHeaders(
          [elb.loadBalancerDnsName, 'elb.wordpress-cdk.tk', cloudfront.domainName])
      ],
      action: aws_elasticloadbalancingv2.ListenerAction.redirect({
        host: 'www.wordpress-cdk.tk',
        permanent: true,
      })
    })
    
    new aws_elasticloadbalancingv2.ApplicationListenerRule(this, 'listener_https_rule', {
      listener: listener_https,
      priority: 10,
      conditions: [
        aws_elasticloadbalancingv2.ListenerCondition.hostHeaders(
          [elb.loadBalancerDnsName, 'elb.wordpress-cdk.tk', cloudfront.domainName])
      ],
      action: aws_elasticloadbalancingv2.ListenerAction.redirect({
        host: 'www.wordpress-cdk.tk',
        permanent: true,
      })
    })
    

確認

curl -v http://Wordp-elb83-1TT135MDVLZ3N-1130701054.ap-northeast-1.elb.amazonaws.com
*   Trying 35.75.128.36:80...
* TCP_NODELAY set
* Connected to Wordp-elb83-1TT135MDVLZ3N-1130701054.ap-northeast-1.elb.amazonaws.com (35.75.128.36) port 80 (#0)
> GET / HTTP/1.1
> Host: Wordp-elb83-1TT135MDVLZ3N-1130701054.ap-northeast-1.elb.amazonaws.com
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: awselb/2.0
< Date: Wed, 04 May 2022 05:21:44 GMT
< Content-Type: text/html
< Content-Length: 134
< Connection: keep-alive
< Location: http://www.wordpress-cdk.tk:80/
< 
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
</body>
</html>
* Connection #0 to host Wordp-elb83-1TT135MDVLZ3N-1130701054.ap-northeast-1.elb.amazonaws.com left intact

curl -v http://elb.wordpress-cdk.tk
*   Trying 54.250.174.110:80...
* TCP_NODELAY set
* Connected to elb.wordpress-cdk.tk (54.250.174.110) port 80 (#0)
> GET / HTTP/1.1
> Host: elb.wordpress-cdk.tk
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: awselb/2.0
< Date: Wed, 04 May 2022 05:22:32 GMT
< Content-Type: text/html
< Content-Length: 134
< Connection: keep-alive
< Location: http://www.wordpress-cdk.tk:80/
< 
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
</body>
</html>
* Connection #0 to host elb.wordpress-cdk.tk left intact

curl -v http://d2rgr0fwcf5dr7.cloudfront.net
*   Trying 18.65.123.50:80...
* TCP_NODELAY set
* Connected to d2rgr0fwcf5dr7.cloudfront.net (18.65.123.50) port 80 (#0)
> GET / HTTP/1.1
> Host: d2rgr0fwcf5dr7.cloudfront.net
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Content-Type: text/html
< Content-Length: 134
< Connection: keep-alive
< Server: awselb/2.0
< Date: Wed, 04 May 2022 05:23:03 GMT
< Location: https://www.wordpress-cdk.tk:443/
< X-Cache: Miss from cloudfront
< Via: 1.1 a9715fbde86b226b6436617aa33710cc.cloudfront.net (CloudFront)
< X-Amz-Cf-Pop: KIX50-P3
< X-Amz-Cf-Id: -H8dpDTFP4ZjsNbpsrtW7UkRKwjolKLPKpzmVm0qTTYfimI5ujZSXA==
< 
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
</body>
</html>
* Connection #0 to host d2rgr0fwcf5dr7.cloudfront.net left intact

curl -v http://www.wordpress-cdk.tk
*   Trying 13.32.50.103:80...
* TCP_NODELAY set
* Connected to www.wordpress-cdk.tk (13.32.50.103) port 80 (#0)
> GET / HTTP/1.1
> Host: www.wordpress-cdk.tk
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Content-Type: text/html; charset=UTF-8
< Content-Length: 0
< Connection: keep-alive
< Date: Wed, 04 May 2022 05:25:39 GMT
< Server: Apache/2.4.53 ()
< X-Powered-By: PHP/7.2.34
< Location: http://www.wordpress-cdk.tk/wp-admin/setup-config.php
< X-Cache: Miss from cloudfront
< Via: 1.1 a2447ed6669558ff303af177568ddb72.cloudfront.net (CloudFront)
< X-Amz-Cf-Pop: NRT57-C1
< X-Amz-Cf-Id: sPrq1LoZtFYma4tCKAdSa_ci7Od9hudO7PTtW0kh0T12axvUllaeGA==
< 
* Connection #0 to host www.wordpress-cdk.tk left intact

Info

この場合も302で転送されていますが、初期設定前なのでWordPressの初期設定画面に転送されています。

HTTPS接続のみに限定する

せっかくSSL対応したので、HTTPでアクセスが来た場合にHTTPSにリダイレクトするように設定しましょう

Danger

WordPressのSSL化設定が完了してからHTTPSのみに限定しましょう。

wordpress-cdk/lib/wordpress-cdk-stack.ts
    const cloudfront = new aws_cloudfront.Distribution(this, 'cloudfront', {
      defaultBehavior: {
        origin: new aws_cloudfront_origins.HttpOrigin("elb.wordpress-cdk.tk"),
        allowedMethods: aws_cloudfront.AllowedMethods.ALLOW_ALL,
        cachedMethods: aws_cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
        viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
        cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
        originRequestPolicy: aws_cloudfront.OriginRequestPolicy.ALL_VIEWER,
      },
      domainNames: ['www.wordpress-cdk.tk'],
      certificate: cloudfront_cert
    })

ViewerProtocolPolicyをALLOW_ALLからREDIRECT_TO_HTTPSに変更するだけです。

curl -v http://www.wordpress-cdk.tk
*   Trying 13.35.49.75:80...
* TCP_NODELAY set
* Connected to www.wordpress-cdk.tk (13.35.49.75) port 80 (#0)
> GET / HTTP/1.1
> Host: www.wordpress-cdk.tk
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: CloudFront
< Date: Wed, 04 May 2022 05:35:34 GMT
< Content-Type: text/html
< Content-Length: 183
< Connection: keep-alive
< Location: https://www.wordpress-cdk.tk/
< X-Cache: Redirect from cloudfront
< Via: 1.1 4da2bc835e000996f0b384c9db0412cc.cloudfront.net (CloudFront)
< X-Amz-Cf-Pop: NRT20-C1
< X-Amz-Cf-Id: fYs-ClGPQl6YUaZrkAe8h30z83xkw7yf1skElwdShSSqcb6hb14luA==
< 
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>CloudFront</center>
</body>
</html>
* Connection #0 to host www.wordpress-cdk.tk left intact

curl -v https://www.wordpress-cdk.tk
*   Trying 13.35.49.75:443...
* TCP_NODELAY set
* Connected to www.wordpress-cdk.tk (13.35.49.75) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_128_GCM_SHA256
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=www.wordpress-cdk.tk
*  start date: May  4 00:00:00 2022 GMT
*  expire date: Jun  3 23:59:59 2023 GMT
*  subjectAltName: host "www.wordpress-cdk.tk" matched cert's "www.wordpress-cdk.tk"
*  issuer: C=US; O=Amazon; OU=Server CA 1B; CN=Amazon
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x5556c248fe10)
> GET / HTTP/2
> Host: www.wordpress-cdk.tk
> user-agent: curl/7.68.0
> accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 302 
< content-type: text/html; charset=UTF-8
< content-length: 0
< location: http://www.wordpress-cdk.tk/wp-admin/setup-config.php
< date: Wed, 04 May 2022 05:36:05 GMT
< server: Apache/2.4.53 ()
< x-powered-by: PHP/7.2.34
< x-cache: Miss from cloudfront
< via: 1.1 d8d967e8190a369930c2613d498c9db8.cloudfront.net (CloudFront)
< x-amz-cf-pop: NRT20-C1
< x-amz-cf-id: F4zOC-9FsS3sA7SDAMHHseItlrbShmyzUCgxCtbzYJgDGXlU1nAqqQ==
< 
* Connection #0 to host www.wordpress-cdk.tk left intact

ソースコード

ソースコード
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { WordpressCdkStack } from '../lib/wordpress-cdk-stack';
import { WordpressCdkUsEast1Stack } from '../lib/wordpress-cdk-stack-us-east-1';

const app = new cdk.App();
new WordpressCdkUsEast1Stack(app, 'WordpressCdkUsEast1Stack', {
  env: {region: 'us-east-1'}  
})

new WordpressCdkStack(app, 'WordpressCdkStack', {
  /* 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. */

  /* 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 },

  /* Uncomment the next line if you know exactly what Account and Region you
   * want to deploy the stack to. */
  // env: { account: '123456789012', region: 'us-east-1' },

  /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
});
import { aws_autoscaling, aws_certificatemanager, aws_cloudfront, aws_cloudfront_origins, aws_ec2, aws_efs, aws_elasticloadbalancingv2, aws_elasticloadbalancingv2_targets, aws_iam, aws_rds, aws_route53, aws_route53_targets, CfnOutput, RemovalPolicy, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

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

    // *****
    // VPC
    // *****

    const vpc = new aws_ec2.Vpc(this, 'VPC', {
      natGateways: 0
    })

    // *****
    // EFS
    // *****

    const efs = new aws_efs.FileSystem(this, 'efs', {
      vpc: vpc,
      removalPolicy: RemovalPolicy.DESTROY,
    })

    // *****
    // EC2
    // *****

    const ec2_sg = new aws_ec2.SecurityGroup(this, 'ec2-sg', {
      vpc: vpc,
    })
    // ec2_sg.addIngressRule(aws_ec2.Peer.anyIpv4(), aws_ec2.Port.tcp(80))

    const ec2_role = new aws_iam.Role(this, 'wordpress-role', {
      assumedBy: new aws_iam.ServicePrincipal('ec2.amazonaws.com'),
      managedPolicies: [
        aws_iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'),
      ],
    })

    const ec2_user_data = new aws_ec2.MultipartUserData()
    const ec2_command = aws_ec2.UserData.forLinux()
    ec2_user_data.addUserDataPart(ec2_command, aws_ec2.MultipartBody.SHELL_SCRIPT, true)
    ec2_command.addCommands(
      "#!/bin/bash",
      "",
      "yum update -y",
      "amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2",
      "yum install -y httpd",
      // efs
      "yum install -y amazon-efs-utils",
      "yum install -y nfs-utils",
      "file_system_id_1=" + efs.fileSystemId,
      "efs_mount_point_1=/var/www/html",
      "mkdir -p \"${efs_mount_point_1}\"",
      "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " +
      "echo \"${file_system_id_1}.efs." + Stack.of(this).region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab",
      "mount -a -t efs,nfs4 defaults",
      // efs
      "systemctl enable httpd",
      "systemctl start httpd",
      "wget https://wordpress.org/latest.tar.gz",
      "tar -xzf latest.tar.gz",
      "cp -r wordpress/* /var/www/html/",
      "chown -R apache /var/www",
      "chgrp -R apache /var/www",
      "chmod 2775 /var/www",
      "find /var/www -type d -exec sudo chmod 2775 {} \;",
      "find /var/www -type f -exec sudo chmod 0644 {} \;",
    )

    const ec2 = new aws_ec2.Instance(this, 'wordpress', {
      vpc: vpc,
      vpcSubnets: { subnetType: aws_ec2.SubnetType.PUBLIC },
      securityGroup: ec2_sg,

      instanceType: aws_ec2.InstanceType.of(aws_ec2.InstanceClass.T3, aws_ec2.InstanceSize.SMALL),
      machineImage: new aws_ec2.AmazonLinuxImage({ generation: aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 }),

      role: ec2_role,

      userData: ec2_user_data
    })

    efs.connections.allowDefaultPortFrom(ec2)

    // *****
    // RDS
    // *****

    const rds = new aws_rds.DatabaseInstance(this, 'Database', {
      vpc: vpc,
      vpcSubnets: {
        subnetType: aws_ec2.SubnetType.PRIVATE_ISOLATED
      },

      multiAz: true,

      engine: aws_rds.DatabaseInstanceEngine.mysql({
        version: aws_rds.MysqlEngineVersion.VER_8_0_28
      }),
      instanceType: aws_ec2.InstanceType.of(aws_ec2.InstanceClass.BURSTABLE4_GRAVITON, aws_ec2.InstanceSize.LARGE),

      databaseName: "wordpress",

      allocatedStorage: 20
    })

    rds.connections.allowDefaultPortFrom(ec2_sg)
    rds.applyRemovalPolicy(RemovalPolicy.DESTROY)

    // *****
    // EC2 Auto Scaling
    // *****

    const asg_user_data = new aws_ec2.MultipartUserData()
    const asg_command = aws_ec2.UserData.forLinux()
    asg_user_data.addUserDataPart(asg_command, aws_ec2.MultipartBody.SHELL_SCRIPT, true)
    asg_command.addCommands(
      "#!/bin/bash",
      "",
      "yum update -y",
      "amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2",
      "yum install -y httpd",
      // efs
      "yum install -y amazon-efs-utils",
      "yum install -y nfs-utils",
      "file_system_id_1=" + efs.fileSystemId,
      "efs_mount_point_1=/var/www/html",
      "mkdir -p \"${efs_mount_point_1}\"",
      "test -f \"/sbin/mount.efs\" && echo \"${file_system_id_1}:/ ${efs_mount_point_1} efs defaults,_netdev\" >> /etc/fstab || " +
      "echo \"${file_system_id_1}.efs." + Stack.of(this).region + ".amazonaws.com:/ ${efs_mount_point_1} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0\" >> /etc/fstab",
      "mount -a -t efs,nfs4 defaults",
      // efs
      "systemctl enable httpd",
      "systemctl start httpd",
      "chown -R apache /var/www",
      "chgrp -R apache /var/www",
      "chmod 2775 /var/www",
      "find /var/www -type d -exec sudo chmod 2775 {} \;",
      "find /var/www -type f -exec sudo chmod 0644 {} \;",
    )

    const asg = new aws_autoscaling.AutoScalingGroup(this, 'asg', {
      vpc: vpc,
      vpcSubnets: { subnetType: aws_ec2.SubnetType.PUBLIC },
      securityGroup: ec2_sg,

      instanceType: aws_ec2.InstanceType.of(aws_ec2.InstanceClass.T3, aws_ec2.InstanceSize.SMALL),
      machineImage: new aws_ec2.AmazonLinuxImage({ generation: aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 }),

      role: ec2_role,

      userData: asg_user_data,

      minCapacity: 1,
      maxCapacity: 2,
      desiredCapacity: 2,

      spotPrice: "0.01"
    })

    efs.connections.allowDefaultPortFrom(asg)

    // *****
    // Route 53
    // *****

    const hostedzone = aws_route53.HostedZone.fromHostedZoneAttributes(this, 'hostedzone', {
      hostedZoneId: 'Z0364500207RRL1KGDBUZ',
      zoneName: 'wordpress-cdk.tk'
    })

    // *****
    // Certificate Manager
    // *****

    const cloudfront_cert = new aws_certificatemanager.DnsValidatedCertificate(this, 'cloudfront_cert', {
      hostedZone: hostedzone,
      domainName: 'www.wordpress-cdk.tk',
      region: 'us-east-1'
    })

    const elb_cert = new aws_certificatemanager.Certificate(this, 'elb_cert', {
      domainName: 'elb.wordpress-cdk.tk',
      validation: aws_certificatemanager.CertificateValidation.fromDns(hostedzone)
    })

    // *****
    // CloudFront
    // *****

    const cloudfront = new aws_cloudfront.Distribution(this, 'cloudfront', {
      defaultBehavior: {
        origin: new aws_cloudfront_origins.HttpOrigin("elb.wordpress-cdk.tk"),
        allowedMethods: aws_cloudfront.AllowedMethods.ALLOW_ALL,
        cachedMethods: aws_cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
        // viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.ALLOW_ALL,
        viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
        cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
        originRequestPolicy: aws_cloudfront.OriginRequestPolicy.ALL_VIEWER,
      },
      domainNames: ['www.wordpress-cdk.tk'],
      certificate: cloudfront_cert
    })

    // *****
    // Elastic Load Balancing
    // *****

    const elb_sg = new aws_ec2.SecurityGroup(this, 'elb-sg', {
      vpc: vpc,
    })

    const elb = new aws_elasticloadbalancingv2.ApplicationLoadBalancer(this, 'elb', {
      vpc: vpc,
      securityGroup: elb_sg,
      internetFacing: true,
    })

    const elb_targetgroup = new aws_elasticloadbalancingv2.ApplicationTargetGroup(this, 'targetgroup', {
      vpc: vpc,
      targets: [new aws_elasticloadbalancingv2_targets.InstanceTarget(ec2)],
      port: 80,
      healthCheck: { enabled: true, healthyHttpCodes: "200-399" },
    })

    asg.attachToApplicationTargetGroup(elb_targetgroup)

    ec2_sg.addIngressRule(aws_ec2.Peer.securityGroupId(elb_sg.securityGroupId), aws_ec2.Port.tcp(80))

    const listener_http = elb.addListener('Listener_http', {
      port: 80,
      open: true,
      defaultTargetGroups: [elb_targetgroup],
    })

    const listener_https = elb.addListener('Listener_https', {
      port: 443,
      open: true,
      certificates: [elb_cert],
      defaultTargetGroups: [elb_targetgroup],
    })

    new aws_elasticloadbalancingv2.ApplicationListenerRule(this, 'listener_http_rule', {
      listener: listener_http,
      priority: 10,
      conditions: [
        aws_elasticloadbalancingv2.ListenerCondition.hostHeaders(
          [elb.loadBalancerDnsName, 'elb.wordpress-cdk.tk', cloudfront.domainName])
      ],
      action: aws_elasticloadbalancingv2.ListenerAction.redirect({
        host: 'www.wordpress-cdk.tk',
        permanent: true,
      })
    })

    new aws_elasticloadbalancingv2.ApplicationListenerRule(this, 'listener_https_rule', {
      listener: listener_https,
      priority: 10,
      conditions: [
        aws_elasticloadbalancingv2.ListenerCondition.hostHeaders(
          [elb.loadBalancerDnsName, 'elb.wordpress-cdk.tk', cloudfront.domainName])
      ],
      action: aws_elasticloadbalancingv2.ListenerAction.redirect({
        host: 'www.wordpress-cdk.tk',
        permanent: true,
      })
    })

    // *****
    // Route 53
    // *****

    new aws_route53.ARecord(this, 'elb-domain', {
      zone: hostedzone,
      recordName: 'elb',
      target: aws_route53.RecordTarget.fromAlias(new aws_route53_targets.LoadBalancerTarget(elb)),
    });

    new aws_route53.ARecord(this, 'cloudfront-domain', {
      zone: hostedzone,
      recordName: 'www',
      target: aws_route53.RecordTarget.fromAlias(new aws_route53_targets.CloudFrontTarget(cloudfront)),
    });

    // *****
    // CloudFormation Output
    // *****

    new CfnOutput(this, 'ec2-output', {
      value: ec2.instancePublicIp
    })
    new CfnOutput(this, 'rds-output', {
      value: rds.dbInstanceEndpointAddress,
    })
    new CfnOutput(this, 'secretsmanager-output', {
      value: rds.secret!.secretName
    })
    new CfnOutput(this, 'elb-output', {
      value: elb.loadBalancerDnsName
    })
    new CfnOutput(this, 'cloudfront-output', {
      value: cloudfront.distributionDomainName
    })

  }
}
import { aws_certificatemanager, aws_route53, Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";

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

        // *****
        // Route 53
        // *****

        const hostedzone = aws_route53.HostedZone.fromHostedZoneAttributes(this, 'hostedzone', {
            hostedZoneId: 'Z0364500207RRL1KGDBUZ',
            zoneName: 'wordpress-cdk.tk'
        })

        // *****
        // Certificate Manager
        // *****

        const cloudfront_cert = new aws_certificatemanager.Certificate(this, 'cloudfront_cert', {
            domainName: 'www.wordpress-cdk.tk',
            validation: aws_certificatemanager.CertificateValidation.fromDns(hostedzone),
        })
    }
}