require 'os' require 'open-uri' module Ruby module Terraform module_function def config @config ||= Configuration.new yield @config if block_given? @config end class Executable class PlatformUnsupported < StandardError; end def initialize(config = Ruby::Terraform.config) @terraform_version = config.terraform_version @download_path = config.download_path @binary = config.binary @download_filename = "#{@terraform_version}-terraform.zip" FileUtils.mkdir_p(@download_path) raise PlatformUnsupported unless supported? end def binary @binary end def download(opts = {}) return if binary_exist? opts[:uri] ||= ENV['TERRAFORM_DOWNLOAD_URL'] || "https://releases.hashicorp.com/#{download_uri}" $stderr.puts("Downloading terraform binary from #{opts[:uri]}") if opts[:verbose] open("#{@download_path}/#{@download_filename}", 'wb') do |saved_file| open(opts[:uri], 'rb') do |read_file| saved_file.write(read_file.read) end end end def extract(opts={}) return if binary_exist? Decompressor.extract("#{@download_path}/#{@download_filename}", @download_path, opts[:verbose] || false) make_exe end private def binary_exist? File.exist?(binary) end def supported? OS.freebsd? || OS.mac? || OS.windows? || OS.linux? end def make_exe FileUtils.chmod('a+x', binary) if binary_exist? && !OS.windows? end def download_uri return "terraform/#{@terraform_version}/terraform_#{@terraform_version}_freebsd_amd64.zip" if OS.freebsd? return "terraform/#{@terraform_version}/terraform_#{@terraform_version}_darwin_amd64.zip" if OS.mac? return "terraform/#{@terraform_version}/terraform_#{@terraform_version}_windows_amd64.zip" if OS.windows? return "terraform/#{@terraform_version}/terraform_#{@terraform_version}_linux_amd64.zip" if OS.linux? end end end end