Skip to content

Instantly share code, notes, and snippets.

@genki
Last active July 21, 2024 22:13
Show Gist options
  • Save genki/6d8fb62dcb7049e2b181c666692f397f to your computer and use it in GitHub Desktop.
Save genki/6d8fb62dcb7049e2b181c666692f397f to your computer and use it in GitHub Desktop.
Invader: A simple preprocessor for terraform
#!/usr/bin/env ruby
# A simple preprocessor for terraform.
#
# USAGE:
#
# invade <template dir> <modules dir>
#
# This script will copy all tf files in the template dir to the modules dir
# and replace the `//invade <invader name> <args>` with the content of the
# invader file located at `./invader/<invader name>.tf`.
# The invader file is a piece of tf file with ERB template.
# The args are formed as `key=value` pairs.
#
require "fileutils"
require "erb"
from = ARGV.shift
to = ARGV.shift
if from.nil? || to.nil?
puts "Usage: #{$0} <from> <to>"
exit 1
end
INVADER_RE = %r{//invade\b(.+?)$}
# load invader files
$invaders = {}
Dir.glob("invader/**/*.tf").each do |path|
name = File.basename(path, ".tf").sub(/^invader\//, "")
$invaders[name] = File.read(path)
end
def invade(src)
src.gsub(INVADER_RE) do |m|
# get indent
_, name, *args = m.split /\s+/
hash = args.reduce({}) do |h, arg|
k, v = arg.split("=")
h[k] = v
h
end
ERB.new($invaders[name]).result_with_hash hash
end
end
Dir.glob("#{from}/**/*.tf").each do |path|
path_to = path.sub(from, to)
dirname = File.dirname(path_to)
FileUtils.mkdir_p(dirname)
src = File.read(path)
dst = invade(src)
File.open(path_to, "w") do |f|
f.write(dst)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment