Skip to content

Instantly share code, notes, and snippets.

@hinorashi
Last active July 18, 2022 12:09
Show Gist options
  • Save hinorashi/c40806a686612b575d25390cdeb13a11 to your computer and use it in GitHub Desktop.
Save hinorashi/c40806a686612b575d25390cdeb13a11 to your computer and use it in GitHub Desktop.
Delete a Route 53 Record with AWS CLI
#!/bin/bash
# =============================================================================================================
# Usage:
# ./route53-delete-record.sh [Hostname] [Type]
# Example:
# ./route53-delete-record.sh test.example.org
# ./route53-delete-record.sh test.example.org TXT
# ./route53-delete-record.sh test.example.org txt
# ./route53-delete-record.sh test.example.org CNAME
# =============================================================================================================
# output coloring
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
CLEAR=$(tput sgr0)
# put your value here
# note that jq can work with env var
HOSTED_ZONE=
DNS_NAME=${1:-test.example.org}
DNS_TYPE=${2:-A}
[[ -z "$HOSTED_ZONE" ]] && HOSTED_ZONE=example.org
# add . to the end
DNS_NAME="$DNS_NAME."
# capitalize
DNS_TYPE=${DNS_TYPE^^}
# find Zone ID
ZONE_ID=$(aws route53 list-hosted-zones-by-name --dns-name $HOSTED_ZONE --output json \
| jq .HostedZones[].Id --raw-output \
| awk -F / '{print $3}')
if [[ -z "$ZONE_ID" ]]; then
echo ${RED}Hosted zone not found!$CLEAR
exit 1
fi
echo Zone ID: $YELLOW$ZONE_ID$CLEAR
echo
# find resource record set
RECORD_SETS=$(aws route53 list-resource-record-sets --hosted-zone-id=$ZONE_ID --output json \
| jq '.ResourceRecordSets[] | select ((.Name == '\"$DNS_NAME\"') and (.Type=='\"$DNS_TYPE\"'))')
if [[ -z "$RECORD_SETS" ]]; then
echo ${RED}No record found!$CLEAR
exit 1
fi
echo Resource Record Sets:
jq <<< "$RECORD_SETS"
echo
# prepare the change batch value
CHANGE_BATCH=$(cat << EOF
{
"Comment": "delete this record",
"Changes": [
{
"Action": "DELETE",
"ResourceRecordSet":
$RECORD_SETS
}
]
}
EOF
)
echo Change batch:
jq <<< "$CHANGE_BATCH"
echo
# perform the deletion
aws route53 change-resource-record-sets --hosted-zone-id=$ZONE_ID --change-batch "$CHANGE_BATCH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment