Module: CliHelper

Defined in:
lib/cli_helper.rb

Overview

Used to handle terraform command options and execution in a consistent way

Class Method Summary collapse

Class Method Details

.execute(command, opts = {}) ⇒ Object

Execute a Terraform command with open3. Supported option is ‘:dir` which is optionally the path to the Terraform project dir



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/cli_helper.rb', line 10

def execute(command, opts = {})
  if opts[:dir]
    begin
      Open3.capture3(command, chdir: opts[:dir])
    rescue Errno::ENOENT => e
      raise TaskHelper::Error.new(e.message, 'terraform/validation-error')
    end
  else
    begin
      Open3.capture3(command)
    rescue Errno::ENOENT => e
      raise TaskHelper::Error.new(e.message, 'terraform/validation-error')
    end
  end
end

.transcribe_to_cli(opts, dir = nil, required = []) ⇒ Object

The apply and destroy CLI opts map from the same task opts to cli opts, share that code.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/cli_helper.rb', line 27

def transcribe_to_cli(opts, dir = nil, required = [])
  cli_opts = ['-no-color']
  cli_opts.push(*required)
  cli_opts << "-state=#{File.expand_path(opts[:state], dir)}" if opts[:state]
  cli_opts << "-state-out=#{File.expand_path(opts[:state_out], dir)}" if opts[:state_out]

  if opts[:target]
    resources = opts[:target].is_a?(Array) ? opts[:target] : Array(opts[:target])
    resources.each { |resource| cli_opts << "-target=#{resource}" }
  end

  opts[:var]&.each { |k, v| cli_opts << "-var '#{k}=#{v}'" }

  if opts[:var_file]
    var_file_paths = opts[:var_file].is_a?(Array) ? opts[:var_file] : Array(opts[:var_file])
    var_file_paths.each { |path| cli_opts << "-var-file=#{File.expand_path(path, dir)}" }
  end

  cli_opts.join(' ')
end