require 'os' require 'open-uri' module Ruby module Terraform module_function def config @config ||= Configuration.new end class Executable class PlatformUnsupported < StandardError; end def initialize(config = Ruby::Terraform.config) @terraform_version = config.terraform_version @download_path = config.download_path @download_filename = "#{@terraform_version}-terraform.zip" FileUtils.mkdir_p(@download_path) raise PlatformUnsupported unless supported? end def binary if OS.windows? "#{@download_path}/terraform.exe" else "#{@download_path}/terraform" end 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 #{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(verbose = false) return if binary_exist? Decompressor.extract("#{@download_path}/#{@download_filename}", @download_path, verbose) 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