Amazon Route53 Construct Library
To add a public hosted zone:
route53.PublicHostedZone(self, "HostedZone",
zone_name="fully.qualified.domain.com"
)
To add a private hosted zone, use PrivateHostedZone
. Note that
enableDnsHostnames
and enableDnsSupport
must have been enabled for the
VPC you’re configuring for private hosted zones.
# vpc: ec2.Vpc
zone = route53.PrivateHostedZone(self, "HostedZone",
zone_name="fully.qualified.domain.com",
vpc=vpc
)
Additional VPCs can be added with zone.addVpc()
.
Adding Records
To add a TXT record to your zone:
# my_zone: route53.HostedZone
route53.TxtRecord(self, "TXTRecord",
zone=my_zone,
record_name="_foo", # If the name ends with a ".", it will be used as-is;
# if it ends with a "." followed by the zone name, a trailing "." will be added automatically;
# otherwise, a ".", the zone name, and a trailing "." will be added automatically.
# Defaults to zone root if not specified.
values=["Bar!", "Baz?"],
ttl=Duration.minutes(90)
)
To add a NS record to your zone:
# my_zone: route53.HostedZone
route53.NsRecord(self, "NSRecord",
zone=my_zone,
record_name="foo",
values=["ns-1.awsdns.co.uk.", "ns-2.awsdns.com."
],
ttl=Duration.minutes(90)
)
To add a DS record to your zone:
# my_zone: route53.HostedZone
route53.DsRecord(self, "DSRecord",
zone=my_zone,
record_name="foo",
values=["12345 3 1 123456789abcdef67890123456789abcdef67890"
],
ttl=Duration.minutes(90)
)
To add an A record to your zone:
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecord",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4", "5.6.7.8")
)
To add an A record for an EC2 instance with an Elastic IP (EIP) to your zone:
# instance: ec2.Instance
# my_zone: route53.HostedZone
elastic_ip = ec2.CfnEIP(self, "EIP",
domain="vpc",
instance_id=instance.instance_id
)
route53.ARecord(self, "ARecord",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses(elastic_ip.ref)
)
To create an A record of type alias with target set to another record created outside CDK:
This function registers the given input i.e. DNS Name(string) of an existing record as an AliasTarget to the new ARecord. To register a target that is created as part of CDK use this instead.
Detailed information can be found in the documentation.
# my_zone: route53.HostedZone
target_record = "existing.record.cdk.local"
record = route53.ARecord.from_aRecord_attributes(self, "A",
zone=my_zone,
record_name="test",
target_dNS=target_record
)
To add an AAAA record pointing to a CloudFront distribution:
import aws_cdk.aws_cloudfront as cloudfront
# my_zone: route53.HostedZone
# distribution: cloudfront.CloudFrontWebDistribution
route53.AaaaRecord(self, "Alias",
zone=my_zone,
target=route53.RecordTarget.from_alias(targets.CloudFrontTarget(distribution))
)
Geolocation routing can be enabled for continent, country or subdivision:
# my_zone: route53.HostedZone
# continent
route53.ARecord(self, "ARecordGeoLocationContinent",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.0", "5.6.7.0"),
geo_location=route53.GeoLocation.continent(route53.Continent.EUROPE)
)
# country
route53.ARecord(self, "ARecordGeoLocationCountry",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.1", "5.6.7.1"),
geo_location=route53.GeoLocation.country("DE")
)
# subdivision
route53.ARecord(self, "ARecordGeoLocationSubDividion",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.2", "5.6.7.2"),
geo_location=route53.GeoLocation.subdivision("WA")
)
# default (wildcard record if no specific record is found)
route53.ARecord(self, "ARecordGeoLocationDefault",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.3", "5.6.7.3"),
geo_location=route53.GeoLocation.default()
)
To enable weighted routing, use the weight
parameter:
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecordWeighted1",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4"),
weight=10
)
To enable latency based routing, use the region
parameter:
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecordLatency1",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4"),
region="us-east-1"
)
To enable multivalue answer routing, use the multivalueAnswer
parameter:
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecordMultiValue1",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4"),
multi_value_answer=True
)
To specify a unique identifier to differentiate among multiple resource record sets that have the same combination of name and type, use the setIdentifier
parameter:
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecordWeighted1",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4"),
weight=10,
set_identifier="weighted-record-id"
)
Warning It is not possible to specify setIdentifier
for a simple routing policy.
Constructs are available for A, AAAA, CAA, CNAME, MX, NS, SRV and TXT records.
Use the CaaAmazonRecord
construct to easily restrict certificate authorities
allowed to issue certificates for a domain to Amazon only.
Health Checks
See the Route 53 Health Checks documentation for possible types of health checks.
Route 53 has the ability to monitor the health of your application and only return records for healthy endpoints.
This is done using a HealthCheck
construct.
In the following example, the ARecord
will be returned by Route 53 in response to DNS queries only if the HTTP requests to the example.com/health
endpoint return a 2XX or 3XX status code.
In case, when the endpoint is not healthy, the ARecord2
will be returned by Route 53 in response to DNS queries.
# my_zone: route53.HostedZone
health_check = route53.HealthCheck(self, "HealthCheck",
type=route53.HealthCheckType.HTTP,
fqdn="example.com",
port=80,
resource_path="/health",
failure_threshold=3,
request_interval=Duration.seconds(30)
)
route53.ARecord(self, "ARecord",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4"),
health_check=health_check,
weight=100
)
route53.ARecord(self, "ARecord2",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("5.6.7.8"),
weight=0
)
Replacing existing record sets (dangerous!)
Use the deleteExisting
prop to delete an existing record set before deploying the new one.
This is useful if you want to minimize downtime and avoid “manual” actions while deploying a
stack with a record set that already exists. This is typically the case for record sets that
are not already “owned” by CloudFormation or “owned” by another stack or construct that is
going to be deleted (migration).
N.B.: this feature is dangerous, use with caution! It can only be used safely when
deleteExisting
is set totrue
as soon as the resource is added to the stack. Changing an existing Record Set’sdeleteExisting
property fromfalse -> true
after deployment will delete the record!
# my_zone: route53.HostedZone
route53.ARecord(self, "ARecord",
zone=my_zone,
target=route53.RecordTarget.from_ip_addresses("1.2.3.4", "5.6.7.8"),
delete_existing=True
)
Cross Account Zone Delegation
If you want to have your root domain hosted zone in one account and your subdomain hosted
zone in a different one, you can use CrossAccountZoneDelegationRecord
to set up delegation
between them.
In the account containing the parent hosted zone:
parent_zone = route53.PublicHostedZone(self, "HostedZone",
zone_name="someexample.com"
)
cross_account_role = iam.Role(self, "CrossAccountRole",
# The role name must be predictable
role_name="MyDelegationRole",
# The other account
assumed_by=iam.AccountPrincipal("12345678901"),
# You can scope down this role policy to be least privileged.
# If you want the other account to be able to manage specific records,
# you can scope down by resource and/or normalized record names
inline_policies={
"cross_account_policy": iam.PolicyDocument(
statements=[
iam.PolicyStatement(
sid="ListHostedZonesByName",
effect=iam.Effect.ALLOW,
actions=["route53:ListHostedZonesByName"],
resources=["*"]
),
iam.PolicyStatement(
sid="GetHostedZoneAndChangeResourceRecordSets",
effect=iam.Effect.ALLOW,
actions=["route53:GetHostedZone", "route53:ChangeResourceRecordSets"],
# This example assumes the RecordSet subdomain.somexample.com
# is contained in the HostedZone
resources=["arn:aws:route53:::hostedzone/HZID00000000000000000"],
conditions={
"ForAllValues:StringLike": {
"route53:ChangeResourceRecordSetsNormalizedRecordNames": ["subdomain.someexample.com"
]
}
}
)
]
)
}
)
parent_zone.grant_delegation(cross_account_role)
In the account containing the child zone to be delegated:
sub_zone = route53.PublicHostedZone(self, "SubZone",
zone_name="sub.someexample.com"
)
# import the delegation role by constructing the roleArn
delegation_role_arn = Stack.of(self).format_arn(
region="", # IAM is global in each partition
service="iam",
account="parent-account-id",
resource="role",
resource_name="MyDelegationRole"
)
delegation_role = iam.Role.from_role_arn(self, "DelegationRole", delegation_role_arn)
# create the record
route53.CrossAccountZoneDelegationRecord(self, "delegate",
delegated_zone=sub_zone,
parent_hosted_zone_name="someexample.com", # or you can use parentHostedZoneId
delegation_role=delegation_role
)
Delegating the hosted zone requires assuming a role in the parent hosted zone’s account.
In order for the assumed credentials to be valid, the resource must assume the role using
an STS endpoint in a region where both the subdomain’s account and the parent’s account
are opted-in. By default, this region is determined automatically, but if you need to
change the region used for the AssumeRole call, specify assumeRoleRegion
:
sub_zone = route53.PublicHostedZone(self, "SubZone",
zone_name="sub.someexample.com"
)
# import the delegation role by constructing the roleArn
delegation_role_arn = Stack.of(self).format_arn(
region="", # IAM is global in each partition
service="iam",
account="parent-account-id",
resource="role",
resource_name="MyDelegationRole"
)
delegation_role = iam.Role.from_role_arn(self, "DelegationRole", delegation_role_arn)
route53.CrossAccountZoneDelegationRecord(self, "delegate",
delegated_zone=sub_zone,
parent_hosted_zone_name="someexample.com", # or you can use parentHostedZoneId
delegation_role=delegation_role,
assume_role_region="us-east-1"
)
Add Trailing Dot to Domain Names
In order to continue managing existing domain names with trailing dots using CDK, you can set addTrailingDot: false
to prevent the Construct from adding a dot at the end of the domain name.
route53.PublicHostedZone(self, "HostedZone",
zone_name="fully.qualified.domain.com.",
add_trailing_dot=False
)
Enabling DNSSEC
DNSSEC can be enabled for Hosted Zones. For detailed information, see Configuring DNSSEC signing in Amazon Route 53.
Enabling DNSSEC requires an asymmetric KMS Customer-Managed Key using the ECC_NIST_P256
key spec.
Additionally, that KMS key must be in us-east-1
.
kms_key = kms.Key(self, "KmsCMK",
key_spec=kms.KeySpec.ECC_NIST_P256,
key_usage=kms.KeyUsage.SIGN_VERIFY
)
hosted_zone = route53.HostedZone(self, "HostedZone",
zone_name="example.com"
)
# Enable DNSSEC signing for the zone
hosted_zone.enable_dnssec(kms_key=kms_key)
The necessary permissions for Route 53 to use the key will automatically be added when using
this configuration. If it is necessary to create a key signing key manually, that can be done
using the KeySigningKey
construct:
# hosted_zone: route53.HostedZone
# kms_key: kms.Key
route53.KeySigningKey(self, "KeySigningKey",
hosted_zone=hosted_zone,
kms_key=kms_key,
key_signing_key_name="ksk",
status=route53.KeySigningKeyStatus.ACTIVE
)
When directly constructing the KeySigningKey
resource, enabling DNSSEC signing for the hosted
zone will be need to be done explicitly (either using the CfnDNSSEC
construct or via another
means).
Imports
If you don’t know the ID of the Hosted Zone to import, you can use the
HostedZone.fromLookup
:
route53.HostedZone.from_lookup(self, "MyZone",
domain_name="example.com"
)
HostedZone.fromLookup
requires an environment to be configured. Check
out the documentation for more documentation and examples. CDK
automatically looks into your ~/.aws/config
file for the [default]
profile.
If you want to specify a different account run cdk deploy --profile [profile]
.
new MyDevStack(app, 'dev', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});
If you know the ID and Name of a Hosted Zone, you can import it directly:
zone = route53.HostedZone.from_hosted_zone_attributes(self, "MyZone",
zone_name="example.com",
hosted_zone_id="ZOJJZC49E0EPZ"
)
Alternatively, use the HostedZone.fromHostedZoneId
to import hosted zones if
you know the ID and the retrieval for the zoneName
is undesirable.
zone = route53.HostedZone.from_hosted_zone_id(self, "MyZone", "ZOJJZC49E0EPZ")
You can import a Public Hosted Zone as well with the similar PublicHostedZone.fromPublicHostedZoneId
and PublicHostedZone.fromPublicHostedZoneAttributes
methods:
zone_from_attributes = route53.PublicHostedZone.from_public_hosted_zone_attributes(self, "MyZone",
zone_name="example.com",
hosted_zone_id="ZOJJZC49E0EPZ"
)
# Does not know zoneName
zone_from_id = route53.PublicHostedZone.from_public_hosted_zone_id(self, "MyZone", "ZOJJZC49E0EPZ")
You can use CrossAccountZoneDelegationRecord
on imported Hosted Zones with the grantDelegation
method:
cross_account_role = iam.Role(self, "CrossAccountRole",
# The role name must be predictable
role_name="MyDelegationRole",
# The other account
assumed_by=iam.AccountPrincipal("12345678901")
)
zone_from_id = route53.HostedZone.from_hosted_zone_id(self, "MyZone", "zone-id")
zone_from_id.grant_delegation(cross_account_role)
public_zone_from_id = route53.PublicHostedZone.from_public_hosted_zone_id(self, "MyPublicZone", "public-zone-id")
public_zone_from_id.grant_delegation(cross_account_role)
private_zone_from_id = route53.PrivateHostedZone.from_private_hosted_zone_id(self, "MyPrivateZone", "private-zone-id")
private_zone_from_id.grant_delegation(cross_account_role)
VPC Endpoint Service Private DNS
When you create a VPC endpoint service, AWS generates endpoint-specific DNS hostnames that consumers use to communicate with the service. For example, vpce-1234-abcdev-us-east-1.vpce-svc-123345.us-east-1.vpce.amazonaws.com. By default, your consumers access the service with that DNS name. This can cause problems with HTTPS traffic because the DNS will not match the backend certificate:
curl: (60) SSL: no alternative certificate subject name matches target host name 'vpce-abcdefghijklmnopq-rstuvwx.vpce-svc-abcdefghijklmnopq.us-east-1.vpce.amazonaws.com'
Effectively, the endpoint appears untrustworthy. To mitigate this, clients have to create an alias for this DNS name in Route53.
Private DNS for an endpoint service lets you configure a private DNS name so consumers can access the service using an existing DNS name without creating this Route53 DNS alias This DNS name can also be guaranteed to match up with the backend certificate.
Before consumers can use the private DNS name, you must verify that you have control of the domain/subdomain.
Assuming your account has ownership of the particular domain/subdomain, this construct sets up the private DNS configuration on the endpoint service, creates all the necessary Route53 entries, and verifies domain ownership.
from aws_cdk.aws_elasticloadbalancingv2 import NetworkLoadBalancer
vpc = ec2.Vpc(self, "VPC")
nlb = NetworkLoadBalancer(self, "NLB",
vpc=vpc
)
vpces = ec2.VpcEndpointService(self, "VPCES",
vpc_endpoint_service_load_balancers=[nlb]
)
# You must use a public hosted zone so domain ownership can be verified
zone = route53.PublicHostedZone(self, "PHZ",
zone_name="aws-cdk.dev"
)
route53.VpcEndpointServiceDomainName(self, "EndpointDomain",
endpoint_service=vpces,
domain_name="my-stuff.aws-cdk.dev",
public_hosted_zone=zone
)