Class: MinimalPipeline::Packer

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

Overview

Here is an example of how to use this class to build AMIs from Packer YAML

“` # Pass in the path to the Packer JSON config file packer = MinimalPipeline::Packer.new('path/to/packer.json')

variables =

'foo' => 'bar',

# Build the AMI and get the new AMI ID new_ami_id = packer.build_ami(variables) “`

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(packer_config, debug = false) ⇒ Packer

Instaniate a Packer object

Parameters:

  • packer_config (String)

    Path to the JSON packer config file

  • debug (Boolean) (defaults to: false)

    Debug mode enabled for packer build (-debug flag)


27
28
29
30
# File 'lib/minimal_pipeline/packer.rb', line 27

def initialize(packer_config, debug = false)
  @config = packer_config
  @debug = debug
end

Instance Attribute Details

#configObject

Returns the value of attribute config.


20
21
22
# File 'lib/minimal_pipeline/packer.rb', line 20

def config
  @config
end

#debugObject

Returns the value of attribute debug.


21
22
23
# File 'lib/minimal_pipeline/packer.rb', line 21

def debug
  @debug
end

Instance Method Details

#build_ami(variables = {}) ⇒ String

Build and execute a packer build command

Parameters:

  • variables (Hash) (defaults to: {})

    Optional key value pairs of packer variables

Returns:

  • (String)

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/minimal_pipeline/packer.rb', line 45

def build_ami(variables = {})
  variable_string = ''

  variables.each_pair do |key, value|
    variable_string += "-var '#{key}=#{value}' "
  end

  command = 'packer -machine-readable build '
  command += '-debug ' if @debug
  command += variable_string unless variable_string.empty?
  command += @config
  puts command if ENV['DEBUG']

  output = ''
  Open3.popen2e(command) do |_stdin, stdouterr, wait_thr|
    while (command_output = stdouterr.gets)
      output += command_output
      puts command_output
      $stdout.flush
    end

    raise 'Packer failed!' unless wait_thr.value.success?
  end

  get_ami_id(output)
end

#get_ami_id(output) ⇒ String

Parse the newly built AMI from a given packer command output

Parameters:

  • output (String)

    The command output of a packer run

Returns:

  • (String)

36
37
38
39
# File 'lib/minimal_pipeline/packer.rb', line 36

def get_ami_id(output)
  return if output.nil? || output.empty?
  output.match(/AMIs were created:.+ (ami-.{17})/)[1]
end