Skip to content

Instantly share code, notes, and snippets.

@pmyjavec
Last active July 17, 2018 05:54
Show Gist options
  • Save pmyjavec/400df6a33e49b856a3da85c03ed9c0ef to your computer and use it in GitHub Desktop.
Save pmyjavec/400df6a33e49b856a3da85c03ed9c0ef to your computer and use it in GitHub Desktop.
Route53 To Terraform
#!/usr/bin/env ruby
#
# Converts a Route53 Zone file into corresponding Terraform resources using pure Ruby, no deps required.
# See usage for more information.
require "json"
require "erb"
require "logger"
Log = Logger.new(STDERR)
Log.level = Logger::ERROR
filename = ARGV[0]
zone_id = ARGV[1]
def convert(filename, zone_id)
begin
Log.info("Loading #{filename}...")
file = File.read(filename)
zone_json = JSON.parse(file)
rescue => e
Log.error("Error loading file #{filename}: #{e}")
end
for rs in zone_json['ResourceRecordSets']
alias_target = rs.has_key?("AliasTarget")
if alias_target
as = rs["AliasTarget"] if alias_target
else
resource_records = rs["ResourceRecords"].map { |v| v["Value"] }
end
template = ERB.new <<-EOF
resource "aws_route53_record" "#{rs['Name'].gsub('.', '_')[0..-2]}" {
zone_id = "#{zone_id}"
name = "#{rs['Name']}"
type = "#{rs['Type']}"
<% if resource_records %>records = #{resource_records} <% end %>
<% if alias_target %>
alias {
name = "#{as["DNSName"]}"
zone_id = "#{as["HostedZoneId"]}"
evaluate_target_health = #{as["EvaluateTargetHealth"]}
}
<% end %>
}
EOF
puts template.result(binding)
end
end
if ARGV.length != 2
puts "Usage: ./route532tf <zone file> <target zone id>"
puts ""
puts "The zone file can be generating by running: aws route53 list-resource-record-sets --hosted-zone-id xxx."
puts "Target zone id is the zone you which to create new TF records against."
exit 1
end
convert(filename, zone_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment