Skip to content

Instantly share code, notes, and snippets.

@mrowe
Created November 15, 2023 04:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrowe/585908827a61e535dd48f461a7569079 to your computer and use it in GitHub Desktop.
Save mrowe/585908827a61e535dd48f461a7569079 to your computer and use it in GitHub Desktop.
from aws_cdk import (
aws_route53 as route53,
aws_route53_targets as targets,
aws_cloudfront as cloudfront,
aws_cloudfront_origins as origins,
aws_certificatemanager as certificatemanager,
Stack
)
from constructs import Construct
'''
A Construct that builds a simple CDN, consisting of a CloudFront
distribution, an SSL Certifcate, and a Route53 CNAME.
It assumes that we already have a hosted zone in which the alias
for the CDN will be created.
The ACM SSL Certificate will be created with DNS validation, also
in the target hosted zone.
Parameters:
- `alias` the DNS name of the CDN endpoint in `zone`
- `zone` the root DNS zone
- `alt_names` any alternative names for the CDN (optional)
- for now, assumed to be in the same root `zone`
- `origin_domain` the fully qualified domain name of the origin
- `origin_path` the path at `origin_domain` to mirror (optional)
'''
class SimpleCDNStack(Stack):
def __init__(self, scope: Construct, id: str, **kwargs) -> None:
ALIAS = kwargs.pop("alias")
ZONE = kwargs.pop("zone")
ORIGIN_DOMAIN = kwargs.pop("origin_domain")
ORIGIN_PATH = kwargs.pop("origin_path", "")
ALT_NAMES = kwargs.pop("alt_names", [])
FQDN = "{0}.{1}".format(ALIAS, ZONE)
ALT_NAMES.append(FQDN)
super().__init__(scope, id, **kwargs)
hosted_zone = route53.HostedZone.from_lookup(self, 'HostedZone',
domain_name=ZONE
)
ssl_certificate = certificatemanager.Certificate(self, "Certificate",
domain_name=FQDN,
subject_alternative_names=ALT_NAMES,
validation=certificatemanager.CertificateValidation.from_dns(hosted_zone=hosted_zone)
)
distribution = cloudfront.Distribution(self, "Distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.HttpOrigin(ORIGIN_DOMAIN, origin_path=ORIGIN_PATH)
),
certificate=ssl_certificate,
domain_names=ALT_NAMES,
comment=FQDN
)
route53.RecordSet(self, "RecordSet",
record_type=route53.RecordType.A,
record_name=ALIAS,
target=route53.RecordTarget.from_alias(targets.CloudFrontTarget(distribution)),
zone=hosted_zone
)
for alias in [a for a in ALT_NAMES if not a == FQDN]:
if not alias.endswith(ZONE):
print("Skipping {} since it's not in {}".format(alias, ZONE))
break
route53.RecordSet(self, "RecordSet-{0}".format(alias),
record_type=route53.RecordType.CNAME,
record_name=alias,
target=route53.RecordTarget.from_values(FQDN),
zone=hosted_zone
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment