Skip to content

Instantly share code, notes, and snippets.

@havenwood
Forked from jedschneider/build.rb
Created May 29, 2024 19:29
Show Gist options
  • Save havenwood/e70a9e654b24cca1e04a915b5fad8301 to your computer and use it in GitHub Desktop.
Save havenwood/e70a9e654b24cca1e04a915b5fad8301 to your computer and use it in GitHub Desktop.
build script for terraform deploys
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'optparse'
require 'fileutils'
require 'open3'
module TerraformExecutor
Config = Struct.new(:parallelism, :init, :vault, :tag, keyword_init: true)
class << self
def apply(args: ARGV, dir: 'terraform/docker')
config = new_config(args)
env = get_env(config)
vault_prefix = prefix(config).to_s
FileUtils.cd(dir)
initialize_terraform(config, env, vault_prefix) if config.init
apply_terraform(config, env, vault_prefix)
end
private
def new_config(args)
config = Config.new(parallelism: 10, init: false, vault: false, tag: nil)
parse(args, config)
raise OptionParser::MissingArgument, 'TARGET' if args.empty?
config
end
def parse(args, config)
OptionParser.new do |parser|
parser.banner = 'Usage: build [options] TARGET'
parser.on('-i', '--init', 'Run terraform init (default: false)')
parser.on('-p', '--parallelism [PARALLELISM]', Integer,
'Run terraform apply with PARALLELISM (default: 10)')
parser.on('-v', '--vault', 'Wrap with aws-vault (default: false)')
parser.on('-t', '--tag IMAGE_TAG', 'Run terraform apply with supplied IMAGE_TAG')
end.parse!(args, into: config)
end
def get_env(config)
env = {
'TF_VAR_github_token' => ENV.fetch('BUNDLE_GITHUB__COM') { `op read "<some 1pass cred>"`.strip }
}
env['<some project>_image_tag'] = config.tag if config.tag
env
end
def prefix(_config) = "aws-vault exec #{ARGV.fetch(0)} --" if config.vault
def initialize_terraform(_config, env_vars, vault_prefix)
FileUtils.rm_rf(%w[.terraform terraform.lock.hcl])
execute_command("#{vault_prefix} terraform init", env_vars)
end
def apply_terraform(config, env_vars, vault_prefix)
execute_command("#{vault_prefix} terraform apply -auto-approve -parallelism=#{config.parallelism}", env_vars)
end
def execute_command(command, env_vars)
puts "Running: '#{command}'"
Open3.popen3(env_vars, command) do |_stdin, stdout, stderr, wait_thr|
IO.copy_stream(stdout, $stdout)
IO.copy_stream(stderr, $stderr)
wait_thr.value
end
rescue StandardError => e
warn "Command execution failed: #{e.message}"
end
end
end
TerraformExecutor.apply
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment