Smarter AWS Route53 Helper
- class smarter.common.helpers.aws.route53.AWSRoute53(aws_access_key_id=None, aws_secret_access_key=None, aws_region=None, aws_profile=None, shared_resource_identifier=None, environment=None, environment_domain=None, root_domain=None, debug_mode=False, init_info=None)[source]
Bases:
AWSBaseProvides a comprehensive, high-level interface for managing AWS Route53 resources within the application.
This helper class abstracts the complexities of interacting directly with the AWS Route53 API, offering a set of convenient methods for common DNS management tasks such as creating, retrieving, updating, and deleting hosted zones and DNS records. By encapsulating these operations, the class enables developers to manage DNS infrastructure programmatically in a consistent and reliable manner.
The class is designed to be used as part of a broader AWS infrastructure management system, leveraging the application’s AWS session and configuration. It ensures that all Route53 operations are performed using the correct credentials and region, as determined by the application’s environment and settings.
Key features include:
Lazy Initialization: The underlying boto3 Route53 client is instantiated only when first needed, reducing unnecessary resource usage and startup time.
Hosted Zone Management: Methods are provided to retrieve existing hosted zones, create new ones if necessary, and delete hosted zones along with their associated records. This simplifies the lifecycle management of DNS zones for dynamic environments.
DNS Record Operations: The class supports creating, updating, retrieving, and deleting DNS records (such as A and NS records) within a hosted zone. It handles the nuances of AWS Route53’s API, including batching changes and waiting for DNS propagation.
Domain Verification: Utilities are included to verify DNS record propagation, accounting for the variable delays inherent in global DNS systems.
Error Handling: Custom exceptions are raised for common failure scenarios, such as missing hosted zones or DNS records, making it easier to diagnose and handle errors in higher-level application logic.
Integration with Application Settings: The class uses application-level settings (such as default TTL) and logging, ensuring that DNS operations are traceable and configurable.
By using this class, developers can automate DNS management tasks as part of deployment, scaling, or teardown workflows, reducing manual intervention and the risk of configuration drift. The class is intended to be subclassed or instantiated as part of a larger AWS infrastructure management toolkit, and is suitable for both production and testing environments.
Example use cases include:
Automatically provisioning DNS records for new application environments or tenants.
Verifying that DNS changes have propagated before proceeding with dependent operations.
Cleaning up DNS resources as part of environment teardown or migration processes.
This design promotes maintainability, reliability, and clarity in DNS management, making Route53 operations accessible and robust for all parts of the application.
- create_domain_a_record(hostname, api_host_domain)[source]
Create an A record in an AWS Route53 hosted zone for a given hostname.
This method creates (or verifies the existence of) an A record for the specified hostname within the Route53 hosted zone associated with the provided parent domain. The A record is created using the values from the environment’s A record, and supports both direct IP and alias target configurations. If the record already exists with the correct values, it is not recreated.
- Parameters:
- Returns:
A tuple containing the created (or existing) DNS record dictionary and a boolean indicating if it was newly created (True) or already existed (False).
- Return type:
- Raises:
AWSHostedZoneNotFound – If the hosted zone or deployment record cannot be found for the given domain.
botocore.exceptions.ClientError – If there is an error communicating with AWS Route53 or creating the record.
- delete_hosted_zone(domain_name)[source]
Delete the AWS Route53 hosted zone and all its DNS record sets for a given domain.
This method locates the hosted zone associated with the specified domain name, deletes all DNS records (except for NS and SOA records), and then deletes the hosted zone itself. This operation is irreversible and will remove all DNS records managed by Route53 for the domain.
- Parameters:
domain_name (
str) – The domain name of the hosted zone to delete.- Returns:
None
- Return type:
- Raises:
AWSHostedZoneNotFound – If the hosted zone for the domain cannot be found.
botocore.exceptions.ClientError – If there is an error communicating with AWS Route53 or deleting resources.
- destroy_dns_record(hosted_zone_id, record_name, record_type='A', record_ttl=600, alias_target=None, record_resource_records=None)[source]
Delete a specific DNS record from an AWS Route53 hosted zone.
This method constructs and submits a change batch to AWS Route53 to delete the specified DNS record from the given hosted zone. The record can be identified by name, type, TTL, and optionally alias target or resource records. If the record does not exist, AWS may raise an error. This operation is irreversible.
- Parameters:
hosted_zone_id (
str) – The ID of the hosted zone containing the DNS record.record_name (
str) – The DNS record name to delete.record_type (
str) – The DNS record type (e.g., “A”, “CNAME”, “NS”).record_ttl (
int) – The TTL (Time to Live) for the DNS record.alias_target (Optional[dict]) – The alias target for the DNS record, if applicable.
record_resource_records (Union[str, List[dict], None]) – The value(s) for the DNS record, which can be a single text value or a list of dictionaries.
- Returns:
None
- Return type:
- Raises:
botocore.exceptions.ClientError – If there is an error communicating with AWS Route53 or deleting the record.
- get_dns_record(hosted_zone_id, record_name, record_type)[source]
Return the DNS record from the hosted zone.
This method retrieves a specific DNS record from the given hosted zone, matching both the record name and type. It searches through all resource record sets in the hosted zone and returns the first record that matches the provided name and type. If no matching record is found, the method returns None.
Example return value:
{ "Name": "example.com.", "Type": "A", "TTL": 300, "ResourceRecords": [ {"Value": "192.1.1.1"} ] }
- get_environment_A_record(domain=None)[source]
Return the DNS A record for the environment domain.
This method retrieves the DNS A record associated with the environment’s domain. If no domain is provided, it uses the default environment domain configured for the application. The returned dictionary contains details about the A record, including the record name, type, TTL, and the list of IP address values.
Example return value:
{ "Name": "example.com.", "Type": "A", "TTL": 300, "ResourceRecords": [{"Value": "192.1.1.1"}] }
- get_hosted_zone(domain_name)[source]
Retrieve the AWS Route53 hosted zone for a given domain name.
This method searches all hosted zones in the AWS account and returns the hosted zone dictionary that matches the provided domain name. The comparison is performed with and without a trailing dot. If no matching hosted zone is found, the method returns None.
- Parameters:
domain_name (str) – The domain name for which to retrieve the hosted zone. Can be with or without a trailing dot.
- Returns:
The hosted zone dictionary if found, otherwise None.
- Return type:
- Raises:
botocore.exceptions.ClientError – If there is an error communicating with AWS Route53.
- get_hosted_zone_by_id(hosted_zone_id)[source]
(NOT IMPLEMENTED) Return the AWS Route53 Hosted zone for the zone id
- Parameters:
hosted_zone_id (str) – The hosted zone ID.
- Returns:
Hosted zone dictionary or None if not found.
- Return type:
Todo
implement this method
- get_hosted_zone_id(hosted_zone)[source]
Extract and return the Route53 hosted zone ID from a hosted zone dictionary.
This method takes a hosted zone dictionary (as returned by AWS Route53 API or get_hosted_zone) and parses out the unique hosted zone ID. The ID is typically found in the ‘Id’ key and may be prefixed with ‘/hostedzone/’. Only the final segment (the actual ID) is returned.
- get_hosted_zone_id_for_domain(domain_name)[source]
Retrieve the AWS Route53 hosted zone ID for a given domain name.
This method ensures that a hosted zone exists for the specified domain name (creating one if necessary), and then extracts and returns the unique hosted zone ID. The domain name is normalized before lookup. If the hosted zone cannot be found or created, an exception is raised.
- get_ns_records(hosted_zone_id)[source]
Return the NS (Name Server) records from the hosted zone.
This method retrieves all NS records associated with the specified hosted zone. The returned value is a list of dictionaries, each representing an NS record set, including the record name, type, TTL, and the list of authoritative name servers.
Example return value:
[ { "Name": "example.com.", "Type": "NS", "TTL": 600, "ResourceRecords": [ {"Value": "ns-2048.awsdns-64.com"}, {"Value": "ns-2049.awsdns-65.net"}, {"Value": "ns-2050.awsdns-66.org"}, {"Value": "ns-2051.awsdns-67.co.uk"} ] } ]
- get_ns_records_for_domain(domain)[source]
Retrieve the NS (Name Server) records for a hosted zone associated with the given domain.
This helper method locates the hosted zone for the specified domain and returns the NS record set, which contains the authoritative name servers for the domain. The returned dictionary includes the record name, type, TTL, and a list of name server values.
Example return value:
{ "Name": "example.com.", "Type": "NS", "TTL": 600, "ResourceRecords": [ {"Value": "ns-2048.awsdns-64.com"}, {"Value": "ns-2049.awsdns-65.net"}, {"Value": "ns-2050.awsdns-66.org"}, {"Value": "ns-2051.awsdns-67.co.uk"} ] }
- get_or_create_dns_record(hosted_zone_id, record_name, record_type, record_ttl, record_alias_target=None, record_value=None)[source]
Get or create the DNS record in the hosted zone.
This method attempts to retrieve a DNS record from the specified hosted zone. If the record exists and matches the provided values or alias target, it is returned along with a flag indicating that it was not created. If the record does not exist or does not match, the method creates or updates the record accordingly. The method waits for the record to be created or updated before returning.
- Parameters:
hosted_zone_id (
str) – The ID of the hosted zone.record_name (
str) – The DNS record name.record_type (
str) – The DNS record type (e.g., “A”, “CNAME”, “NS”).record_ttl (
int) – The TTL (Time to Live) for the DNS record.record_alias_target (
Optional[dict]) – The alias target for the DNS record, if applicable.record_value (
Optional[dict]) – The value(s) for the DNS record, which can be a single text value or a list of dictionaries.
- Returns:
A tuple containing the DNS record dictionary and a boolean indicating whether the record was created (True) or already existed (False).
- Return type:
- get_or_create_hosted_zone(domain_name)[source]
Retrieve an existing hosted zone for the given domain, or create one if it does not exist.
This method checks if a Route53 hosted zone exists for the specified domain name. If the hosted zone is found, it is returned along with a boolean flag indicating that it was not newly created. If the hosted zone does not exist, the method creates a new public hosted zone for the domain, waits for its creation, and then returns the new hosted zone along with a boolean flag indicating creation.
The returned dictionary contains details about the hosted zone and its delegation set, including the hosted zone ID, name, configuration, and the list of authoritative name servers.
Example return value:
{ "HostedZone": { "Id": "/hostedzone/Z148QEXAMPLE8V", "Name": "example.com.", "CallerReference": "my hosted zone", "Config": { "Comment": "This is my hosted zone", "PrivateZone": false }, "ResourceRecordSetCount": 2 }, "DelegationSet": { "NameServers": [ "ns-2048.awsdns-64.com", "ns-2049.awsdns-65.net", "ns-2050.awsdns-66.org", "ns-2051.awsdns-67.co.uk" ] } }
- Parameters:
domain_name (str) – The domain name for which to retrieve or create the hosted zone.
- Returns:
A tuple containing the hosted zone dictionary and a boolean indicating if it was created.
- Return type:
- Raises:
AWSHostedZoneNotFound – If the hosted zone could not be found or created.
- verify_dns_record(domain_name)[source]
Verify the DNS record for the given domain name.
DNS propagation can take a variable amount of time depending on the DNS provider and geographic location. For example, in some regions it may take up to an hour for AWS Route53 records to propagate, while within an AWS VPC it typically takes less than 5 minutes. This method attempts to resolve the domain’s A record every 60 seconds for up to 15 minutes, allowing for DNS propagation delays.
Note that other Kubernetes functions or AWS services that depend on DNS records may be able to see the records before they are visible from your current location.