#! /bin/bash # # Translates an existing AWS Route53 zone into Terraform `aws_route53_record` resources. # # Released under the MIT license; YMMV. Tested on Linux with: # # - jq-1.6 # - terraform v0.12.26 # - aws-cli/1.17.14 # # The base filename for both the TF resources and the import script OUTNAME=route53_records # Your AWS Zone ID ZONE_ID=ABC123 # The Terraform variable to reference in aws_route53_record entries ZONE_VAR=aws_route53_zone.MY_RESOURCE.zone_id as_tf_route53_record_dns_name() { local name="$1" echo $name | sed 's/\\052/*/' } as_tf_route53_record_resource_name() { local name="$1" local type=$2 echo $name | grep -i '^[a-z_]' > /dev/null || { # Terraform requires resource names to start with an alpha character or # underscore. This one didn'ts, but we can fix that. name="_${name}" } echo "$(echo $name | tr '.' '-' | sed 's/\\052/wildcard/')$(echo $type | tr '[:upper:]' '[:lower:]')" } as_tf_route53_alias() { local alias=$1 cat < ${OUTNAME}_import.sh chmod +x ${OUTNAME}_import.sh aws route53 list-resource-record-sets \ --hosted-zone-id=$ZONE_ID \ | jq -c '.ResourceRecordSets[]' \ | while IFS= read -r line do as_tf_route53_record "$line" >> ${OUTNAME}.txt as_tf_route53_record_import "$line" >> ${OUTNAME}_import.sh done echo "Zone retrieved from Route 53!" echo echo "Copy the resources from ${OUTNAME}.txt into main.tf, then import existing" echo "records using:" echo echo " $ ./${OUTNAME}_import.sh" echo