I needed to migrate from Namecheap’s DNS to Cloudflare’s, as I like it more, it propagates faster and Terraform supports it natively. The following script will talk to Namecheap’s API and print all your records in a Terraform-compatible format.

#!/usr/bin/env python

import random
import string
import sys
from collections import OrderedDict

from namecheap import Api

def random_id():
    return "".join([random.choice(string.ascii_lowercase) for _ in range(8)])

def main():
    if len(sys.argv) != 2:
        print("Usage:\n    migrate_from_namecheap.py <domain>")

    username = input("Enter your Namecheap username: ")
    api_key = input("Enter your Namecheap API key: ")
    api = Api(username, api_key, username, "", sandbox=False, debug=False)

    records = api.domains_dns_getHosts(sys.argv[1])

    for record in records:
        info = OrderedDict()

        info["domain"] = "${var.domain}"
        info["proxied"] = "false"
        info["type"] = record["Type"]
        info["name"] = record["Name"]
        info["value"] = record["Address"].rstrip(".")

        if info["type"] == "MX":
            info["priority"] = record["MXPref"]

        fields = "\n".join(["    %s = \"%s\"" % (key, value) for key, value in info.items()])

        entry = """resource "cloudflare_record" "%s" {\n%s\n}\n""" % (random_id(), fields)

if __name__ == "__main__":