Class: TFEnv::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/tfenv/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ CLI


8
9
10
# File 'lib/tfenv/cli.rb', line 8

def initialize(*args)
  @args = args
end

Instance Method Details

#collate_outputs(options) ⇒ Object


66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tfenv/cli.rb', line 66

def collate_outputs(options)
  {}.tap do |outputs|
    options[:includes].each do |state_file|
      outputs.merge!(read_outputs(state_file))
    end

    options[:consuls].each do |consul_uri|
      outputs.merge!(read_consul_uri(consul_uri))
    end
  end
end

#export_hash(hash) ⇒ Object


12
13
14
15
16
# File 'lib/tfenv/cli.rb', line 12

def export_hash(hash)
  hash.each do |key, value|
    ENV["TF_VAR_#{key}"] = value
  end
end

#load_outputs(options) ⇒ Object


78
79
80
81
82
83
84
85
86
87
88
# File 'lib/tfenv/cli.rb', line 78

def load_outputs(options)
  {}.tap do |outputs|
    if options[:includes].empty? && options[:consuls].empty?
      if File.exists?("terraform.tfstate")
        return read_outputs("terraform.tfstate")
      end
    else
      collate_outputs(options)
    end
  end
end

#parse_optionsObject


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tfenv/cli.rb', line 37

def parse_options
  options = {
    :includes => [],
    :consuls => []
  }

  OptionParser.new do |opts|
    opts.banner = "Usage: tfenv [options] [command]"

    opts.on("-s", "--state-file FILE", "Include external state output from state file") do |v|
      options[:includes] << v
    end

    opts.on("-c", "--consul URL/KEY", "Include external state output from consul") do |v|
      options[:consuls] << v
    end

    opts.on("-t", "--tfvar FILE", "Write variables to tfvar file") do |v|
      options[:tfvar] = v
    end

    opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
      options[:verbose] = v
    end
  end.parse!

  options
end

#read_consul_uri(uri) ⇒ Object


18
19
20
# File 'lib/tfenv/cli.rb', line 18

def read_consul_uri(uri)
  raise "Not implemented"
end

#read_outputs(state_file) ⇒ Object


22
23
24
25
26
27
28
29
30
# File 'lib/tfenv/cli.rb', line 22

def read_outputs(state_file)
  {}.tap do |outputs|
    read_state(state_file).tap do |state|
      state["modules"].each do |module_state|
        outputs.merge!(module_state["outputs"])
      end
    end
  end
end

#read_state(state_file) ⇒ Object


32
33
34
35
# File 'lib/tfenv/cli.rb', line 32

def read_state(state_file)
  raw_state = File.read(state_file)
  JSON.parse(raw_state)
end

#startObject


90
91
92
93
94
95
96
97
98
99
100
# File 'lib/tfenv/cli.rb', line 90

def start
  options = parse_options
  outputs = load_outputs(options)

  if ARGV.length > 0
    export_hash(outputs)
    exec(*ARGV)
  else
    puts outputs.to_yaml
  end
end