Skip to content

Instantly share code, notes, and snippets.

@mmiranda
Created January 7, 2021 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmiranda/028b08014ec185bfe1960b1b38d0456f to your computer and use it in GitHub Desktop.
Save mmiranda/028b08014ec185bfe1960b1b38d0456f to your computer and use it in GitHub Desktop.
Compare AWS Route53 records with Terraform state
#!/bin/bash
###################################################################
#Script Name : route53-terraform-compare
#Description : Compare both Route53 records and Terraform state and check what is missing in state
#Args : -z ZONE_ID -p /path/to/tf-state
#Author : Mateus Miranda
#Email : mateusmiranda@gmail.com
###################################################################
usage() { echo "Usage: $0 [-z ZONE_ID] [-p /path/to/tf-state]" 1>&2; exit 1; }
while getopts ":z:p:" o; do
case "${o}" in
z)
ZONE_ID=${OPTARG}
;;
p)
PATH_STATE=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ -z "${ZONE_ID}" ] || [ -z "${PATH_STATE}" ]; then
usage
fi
# Get All resources in Route53
aws route53 list-resource-record-sets --hosted-zone-id $ZONE_ID > /tmp/route53-records-$ZONE_ID-raw.log
# Get attr Name of records, ignoring TXT records
cat /tmp/route53-records-$ZONE_ID-raw.log | jq '.ResourceRecordSets[] | select(.Type != "TXT")' | jq '.Name' > /tmp/route53-records-$ZONE_ID.log
# Clean last "." in the records
sed -i.bak 's/.\"/\"/g' /tmp/route53-records-$ZONE_ID.log
# Fetch Terraform remote state
cd $PATH_STATE
terraform state pull > /tmp/terraform-state-$ZONE_ID-raw.log
# Grab only the records (FQDN)
cat /tmp/terraform-state-$ZONE_ID-raw.log | jq '.modules[].resources' | jq '.[].primary.attributes.fqdn' > /tmp/terraform-state-$ZONE_ID.log
# Compare both (ignore k8s pattern)
echo "Those are the records in Route53 for Zone ID ${ZONE_ID} that is not managed by Terraform"
echo ""
join -v 2 <(sort /tmp/terraform-state-$ZONE_ID.log) <(sort /tmp/route53-records-$ZONE_ID.log) | grep -v k8s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment