Logo

dev-resources.site

for different kinds of informations.

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

Published at
11/26/2024
Categories
route53
dns
migrate
aws
Author
nowsathk
Categories
4 categories in total
route53
open
dns
open
migrate
open
aws
open
Author
8 person written this
nowsathk
open
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.
route53 Article's
30 articles in total
Favicon
Dominio personalizado en Amazon API Gateway. Dominio desde GoDaddy.
Favicon
How to Simplify DNS Management in a Multi-Account Environment with Route 53 Resolver
Favicon
How to Add an Elastic (Static) IP to Your EC2 Instance And Update Your DNS Records on Route53
Favicon
Amazon Route 53: AWS's Powerful DNS Service ๐ŸŒ๐Ÿš€
Favicon
AWS Private Zones To The Max
Favicon
Migrate a hosted zone to a different AWS account in few seconds!!
Favicon
Before You Dive into Route 53: Learn These DNS Terms
Favicon
How to Add DNS Records for Your Domain in Route53
Favicon
How to Set Up a Public Hosted Zone on Amazon Route 53 When Your Domain Is Registered with Another Registrar
Favicon
Convert http to https in AWS
Favicon
Amazon Route 53 Resolver endpoints now support DNS-over-HTTPS (DoH) with Server Name Indication (SNI) validation
Favicon
Automated DNS Record Management for Kubernetes Resources using external-dns and AWS Route53
Favicon
Automating AWS DNS Firewall Domain List Updates Using S3, Lambda, and CLI
Favicon
Issue 65 of AWS Cloud Security Weekly
Favicon
Unlocking the Power of AWS Route 53: Your Complete Guide to DNS Management
Favicon
How to Use AWS Route 53 for Free
Favicon
Setup AWS EC2 and Configure Route 53: Domain Redirection Made Easy!
Favicon
Deploying Static Website to AWS: A Step-by-Step Guide with S3, Route 53, and CloudFront
Favicon
Cross-Account VPC Associations with Route53 Private Hosted Zone and Addressing Terraform State Update Issue
Favicon
AWS Route53: A Beginnerโ€™s Guide
Favicon
Configuring a Custom Domain for API Gateway with AWS Cloud Development Kit (CDK): SSL Certificate Use and Route 53 Integration
Favicon
How to Host a Static Website on AWS Using S3, Route 53, CloudFront, and Certificate Manager
Favicon
Managing your GoDaddy domain with Route53
Favicon
Using a custom domain name in a Private REST API Gateway
Favicon
How to migrate DNS records from CloudFlare to AWS Route53 with Terraform&Terragrunt
Favicon
Multi-Account/Environment DNS Zones
Favicon
Creating a custom domain name for AWS Elastic Beanstalk application
Favicon
Failover Mechanism in Amazon Route 53 Private Hosted Zones
Favicon
Free dynDNS for your NAS: auto-update DNS with your latest IP
Favicon
Advanced Techniques in AWS API Gateway and Route 53

Featured ones: