Skip to content

Instantly share code, notes, and snippets.

@g3rhard
Forked from ramsey/r53export.sh
Created August 27, 2018 11:24
Show Gist options
  • Save g3rhard/b1618073566861fd13b3de0225a36e04 to your computer and use it in GitHub Desktop.
Save g3rhard/b1618073566861fd13b3de0225a36e04 to your computer and use it in GitHub Desktop.
Queries AWS Route53 for a zone name and outputs a zone file of its records
#!/bin/bash
#
# Queries AWS Route53 for a zone name and outputs a zone file of its records
#
# Usage:
#
# r53export example.com[ profile]
#
# By default, uses $AWS_PROFILE environment variable, if set.
#
#
# Dependencies:
#
# * AWS Command Line Interface, <https://aws.amazon.com/cli/>
# * ./jq, <https://stedolan.github.io/jq/>
# * ~/.aws/config file divided into profiles; see `aws configure help`
#
#
# Copyright 2018 Ben Ramsey <ben@benramsey.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
zonename=$1
profile="${2:-$AWS_PROFILE}"
echo "; Using AWS profile ${profile}"
jq_getzoneid=$(cat <<EOF
.HostedZones[]
| select(.Name == "${zonename}.")
| .Id
| ltrimstr("/hostedzone/")
EOF
)
hostedzones=$(aws --profile "${profile}" route53 list-hosted-zones)
hostedzoneid=$(echo "$hostedzones" | jq -r "$jq_getzoneid")
echo -e "; Hosted zone ID: ${hostedzoneid}\n"
zone_records=$(
aws --profile "${profile}" route53 \
list-resource-record-sets \
--hosted-zone-id "${hostedzoneid}" \
--output json
)
jq_dnsvalue=$(cat <<EOF
if (.ResourceRecords) != null then
(.ResourceRecords[].Value)
else (
if (.AliasTarget) != null then
"\(.AliasTarget.DNSName) ; HostedZoneId: \(.AliasTarget.HostedZoneId)"
else
""
end
) end
EOF
)
jq_parsezone=$(cat <<EOF
.ResourceRecordSets[]
|
"\(.Name)\t"
+ "\(if (.TTL) == null then "" else (.TTL) end)\t"
+ "IN\t"
+ "\(if (.AliasTarget != null) then "ALIAS" else (.Type) end)\t"
+ "\($jq_dnsvalue)"
EOF
)
echo "$zone_records" | jq -r "$jq_parsezone"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment