Last active
July 17, 2018 05:54
-
-
Save pmyjavec/400df6a33e49b856a3da85c03ed9c0ef to your computer and use it in GitHub Desktop.
Route53 To Terraform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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