Class: Terraform

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = nil, state = '') ⇒ Terraform

Returns a new instance of Terraform.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
# File 'lib/terraform.rb', line 8

def initialize(config=nil, state='')
  raise ArgumentError.new('You must pass in a config string') if !config

  @config = config
  @state = state
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



6
7
8
# File 'lib/terraform.rb', line 6

def config
  @config
end

#outputObject

Returns the value of attribute output.



6
7
8
# File 'lib/terraform.rb', line 6

def output
  @output
end

#stateObject

Returns the value of attribute state.



6
7
8
# File 'lib/terraform.rb', line 6

def state
  @state
end

Instance Method Details

#applyObject



15
16
17
# File 'lib/terraform.rb', line 15

def apply
  run_command('apply')
end

#destroyObject



23
24
25
26
# File 'lib/terraform.rb', line 23

def destroy
  return 'You must pass in a state to destroy' if @state.empty?
  run_command(['destroy', '-force'].join(' '))
end

#planObject



19
20
21
# File 'lib/terraform.rb', line 19

def plan
  run_command('plan')
end

#run_command(command) ⇒ Object

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/terraform.rb', line 28

def run_command(command)
  raise ArgumentError.new('Can\'t find tmp/ directory to write files to') if !Dir.exist?('tmp')

  dir = "tmp/terraform-#{time_now}"
  file = "#{time_now}.tf"

  # create directory
  Dir.mkdir(dir)

  # write config file
  File.open("#{dir}/#{file}", 'w') { |f| f.write(@config) }

  # write state file if we have state
  state_path = "#{dir}/terraform.tfstate"
  if !@state.empty?
    File.open(state_path, 'w') { |f| f.write(@state) }
  end

  line = Cocaine::CommandLine.new("cd #{dir} && terraform #{command}", '', logger: Logger.new(STDOUT))
  line.run
  @output = line.output.output

  if File.exists?(state_path)
    @state = File.read(state_path)
  end

  FileUtils.rm_r(dir, force: true)
  
  return @output
end

#time_nowObject



59
60
61
# File 'lib/terraform.rb', line 59

def time_now
  Time.now.strftime('%m%e%y%H%M%S')
end