DEV Community

Cover image for Migrate a hosted zone to a different AWS account in few seconds!!
Nowsath for AWS Community Builders

Posted on

Migrate a hosted zone to a different AWS account in few seconds!!

Migrating a hosted zone from one AWS account to another involves creating a new hosted zone in the target account, replicating the DNS records, and updating the domain's nameservers. Here's a step-by-step guide for manual and automated steps.

-- Manual Steps --

In this process, will guide you through migrating a hosted zone using the AWS CLI.

1. Export DNS Records from the Source Account

i. Install AWS CLI if not already installed.
ii. Use the following command to export the DNS records from the hosted zone in the source account:

aws route53 list-resource-record-sets --hosted-zone-id <source-hosted-zone-id> > dns-records.json
Enter fullscreen mode Exit fullscreen mode

iii. Save the output file (dns-records.json), which contains all DNS records.

2. Create a New Hosted Zone in the Target Account

  1. Log in to the target AWS account.
  2. Navigate to Route 53 and create a new hosted zone with the same domain name.
  3. Note the new hosted zone ID and nameservers assigned to the zone.

3. Import DNS Records to the Target Account

i. Use the exported dns-records.json to replicate the records.
ii. Transform the JSON file to match the change-resource-record-sets API format if needed. An example format looks like this:

{
    "Changes": [
        {
            "Action": "CREATE",
            "ResourceRecordSet": {
                "Name": "example.com.",
                "Type": "A",
                "TTL": 300,
                "ResourceRecords": [
                    {
                        "Value": "192.0.2.1"
                    }
                ]
            }
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

iii. Import the records to the new hosted zone:

aws route53 change-resource-record-sets --hosted-zone-id <new-hosted-zone-id> --change-batch file://dns-records.json
Enter fullscreen mode Exit fullscreen mode

4. Update the Domain's Nameservers

i. Go to your domain registrar (e.g., AWS Route 53, GoDaddy, Namecheap).
ii. Replace the nameservers with the ones provided in the new hosted zone.
iii. Wait for the DNS propagation, which can take up to 48 hours.

5. Verify the Migration

i. Use tools like DNS Checker to ensure the records are correctly propagating.
Confirm that the DNS records are functional and resolving to the expected values.

Tips

  • Avoid downtime: Keep both hosted zones active until propagation is complete.
  • Delegate permissions: If you need cross-account access, consider using AWS Resource Access Manager (RAM) or an IAM role for temporary access.
  • Automate the process: Use tools like Terraform or Route 53's APIs for larger migrations.

-- Automated Steps --

Here’s a Python script using boto3 (AWS SDK for Python) to automate the transformation and migration of DNS records between AWS accounts. This script will:

  1. Export DNS records from the source account.
  2. Transform them into the format required for importing.
  3. Import the records into the target account.

Prerequisites

i. Install the required libraries:

pip3 install boto3
Enter fullscreen mode Exit fullscreen mode

ii. Set up AWS CLI profiles for both accounts:

  • Source account: aws configure --profile source_account
  • Target account: aws configure --profile target_account

iii. Save the python script as migrate_dns.py

import boto3
import json

# Constants
SOURCE_PROFILE = "source_account"
TARGET_PROFILE = "target_account"
SOURCE_HOSTED_ZONE_ID = "source-hosted-zone-id"
TARGET_HOSTED_ZONE_ID = "target-hosted-zone-id"

def export_dns_records():
    """Export DNS records from the source hosted zone."""
    session = boto3.Session(profile_name=SOURCE_PROFILE)
    client = session.client("route53")
    response = client.list_resource_record_sets(HostedZoneId=SOURCE_HOSTED_ZONE_ID)

    # Save records to a file
    with open("dns_records.json", "w") as f:
        json.dump(response["ResourceRecordSets"], f, indent=4)
    print("DNS records exported to dns_records.json")

def transform_records():
    """Transform DNS records for importing to the target hosted zone."""
    with open("dns_records.json", "r") as f:
        records = json.load(f)

    changes = []
    for record in records:
        # Skip NS and SOA records
        if record["Type"] in ["NS", "SOA"]:
            continue

        change = {
            "Action": "CREATE",
            "ResourceRecordSet": {
                "Name": record["Name"],
                "Type": record["Type"],
                "TTL": record.get("TTL", 300),  # Default TTL
                "ResourceRecords": record.get("ResourceRecords", [])
            }
        }
        changes.append(change)

    # Save transformed records to a file
    with open("transformed_records.json", "w") as f:
        json.dump({"Changes": changes}, f, indent=4)
    print("Records transformed and saved to transformed_records.json")

def import_dns_records():
    """Import transformed DNS records into the target hosted zone."""
    session = boto3.Session(profile_name=TARGET_PROFILE)
    client = session.client("route53")

    with open("transformed_records.json", "r") as f:
        change_batch = json.load(f)

    response = client.change_resource_record_sets(
        HostedZoneId=TARGET_HOSTED_ZONE_ID,
        ChangeBatch=change_batch
    )
    print("DNS records imported successfully")
    print(f"Change info: {response['ChangeInfo']}")

if __name__ == "__main__":
    # Step 1: Export DNS records from source account
    export_dns_records()

    # Step 2: Transform records for the target account
    transform_records()

    # Step 3: Import DNS records into the target account
    import_dns_records()
Enter fullscreen mode Exit fullscreen mode

How to Use

i. Replace source-hosted-zone-id and target-hosted-zone-id with the respective hosted zone IDs. Also replace profiles if you have created differently.
ii. Run the script:

python migrate_dns.py
Enter fullscreen mode Exit fullscreen mode

Key Notes

  • SOA and NS records are skipped: These are automatically managed by AWS.
  • TTL fallback: If a record lacks a TTL, a default value of 300 seconds is applied.

Top comments (0)