Class: TerraformDevKit::TerraformInstaller

Inherits:
Object
  • Object
show all
Defined in:
lib/TerraformDevKit/terraform_installer.rb

Constant Summary collapse

LOCAL_FILE_NAME =
'terraform.zip'.freeze

Class Method Summary collapse

Class Method Details

.download_terraform(version) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/TerraformDevKit/terraform_installer.rb', line 42

def self.download_terraform(version)
  TerraformDevKit.download_file(
    "https://releases.hashicorp.com/terraform/#{version}/terraform_#{version}_#{OS.host_os}_amd64.zip",
    LOCAL_FILE_NAME,
    force_download: true
  )
end

.extract_version(output) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/TerraformDevKit/terraform_installer.rb', line 18

def self.extract_version(output)
  # Terraform vx.y.z might be anywhere in the output (warnings may appear
  # before the version does). Therefore we scan all the lines.

  matches = output.map { |line| /Terraform v(\d+\.\d+\.\d+)/.match(line) }
                  .reject(&:nil?)

  matches.count == 1 ? matches[0][1] : nil
end

.install_local(version, directory: Dir.pwd) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/TerraformDevKit/terraform_installer.rb', line 28

def self.install_local(version, directory: Dir.pwd)
  if installed_terraform_version == version
    puts 'Terraform already installed'
    return
  end

  FileUtils.mkdir_p(directory)
  Dir.chdir(directory) do
    download_terraform(version)
    unzip_terraform
  end
end

.installed_terraform_versionObject



12
13
14
15
16
# File 'lib/TerraformDevKit/terraform_installer.rb', line 12

def self.installed_terraform_version
  extract_version(Command.run('terraform --version'))
rescue
  nil
end

.unzip_terraformObject



51
52
53
54
55
56
57
58
59
# File 'lib/TerraformDevKit/terraform_installer.rb', line 51

def self.unzip_terraform
  Zip::File.open(LOCAL_FILE_NAME) do |zip_file|
    zip_file.each do |entry|
      puts "Extracting #{entry.name}"
      entry.restore_permissions = true
      entry.extract(entry.name) { true }
    end
  end
end