Class: Pfm::Command::Base

Inherits:
Object
  • Object
show all
Includes:
Mixlib::CLI, Helpers
Defined in:
lib/iapi-idlc-sdk-pfm/command/base.rb

Defined Under Namespace

Classes: BuildFailure, DeploymentFailure, InvalidRepository

Instance Method Summary collapse

Methods included from Helpers

debug, err, msg, system_command

Constructor Details

#initializeBase

Returns a new instance of Base.



35
36
37
38
39
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 35

def initialize
  super

  @workspace = Idlc::Workspace.new
end

Instance Method Details

#build_base_dirObject



222
223
224
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 222

def build_base_dir
  "#{SETTINGS['BUILD_BASE_DIR']}/#{@params.first}"
end

#build_dirObject



230
231
232
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 230

def build_dir
  "#{@workspace.tmp_dir}/#{build_base_dir}".freeze
end

#build_exists?Boolean

Returns:

  • (Boolean)


234
235
236
237
238
239
240
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 234

def build_exists?
  return true if Dir.exist? build_base_dir

  # doesn't exist
  @errors.push("Build::#{@params.first} doesnt exist")
  false
end

#build_setupObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 71

def build_setup
  Packer::Binary.configure do |config|
    config.version = SETTINGS['PACKER_VERSION']
    config.download_path = "/tmp/#{SecureRandom.uuid}"
  end

  @build_config = Idlc::Build::Config.new(SETTINGS['AWS_REGION'])
  @workspace.add(build_base_dir)

  build_dir = "#{@workspace.tmp_dir}/#{build_base_dir}".freeze

  msg("Using build template: Build::#{@params.first}::#{@config[:build_template]}::#{@config[:build_metadata]}")

  # Include build metadata
  @build_metadata = Idlc::Build::Metadata.new(@params.first, @config[:build_metadata])

  # load the rest of the metadata
  @build_metadata.load

  # load version from command line if specified
  @build_metadata.attributes['version'] = Idlc::Build::Metadata::MetadataAttribute.new(@config[:build_version], true) unless @config[:build_version].nil?

  # check metadata requirements
  @build_metadata.requirements_satisfied?

  msg("Template Version: #{@build_metadata.attributes['version'].value}")

  @build_metadata.attributes.each do |key, att|
    # load metadata file as packer user vars
    @build_config.add_build_var_v2(key, att.value)
  end

  # Copy over the base template and auxillary files for Packer
  tpl = Idlc::Build::Template.new(
    @build_metadata.attributes,
    "#{build_dir}/build.json"
  )
  tpl.write

  # copy auxiliary files
  system("cp -a #{templates_dir}/files #{build_dir}")

  Dir.chdir(build_dir)
end

#deploy_setupObject

Raises:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 116

def deploy_setup
  Terraform::Binary.configure do |config|
    config.version = SETTINGS['TERRAFORM_VERSION']
    config.download_path = "/tmp/#{SecureRandom.uuid}"
  end

  raise InvalidRepository, 'This doesn\'t look like a valid infrastructure repository' unless File.directory? "#{inf_base_dir}/tf"
  config = Idlc::Deploy::Config.new(SETTINGS['AWS_REGION'])

  config.parse("#{inf_base_dir}/env/config/default.yml") if File.exist? "#{inf_base_dir}/env/config/default.yml"

  if ENV['PROD'] == 'true' || ENV['PROD'] == '1'
    config.parse("#{inf_base_dir}/env/config/prod.yml")
  else
    config.parse("#{inf_base_dir}/env/config/devtest.yml")
  end

  config.parse("#{inf_base_dir}/env/size/#{ENV['SIZE']}.yml") if File.exist? "#{inf_base_dir}/env/size/#{ENV['SIZE']}.yml"

  inf_conf_file = 'inf.config.yml'

  # For unit tests
  inf_conf_file = 'inf.config.example.yml' unless File.exist? inf_conf_file
  config.parse(inf_conf_file)

  bucket_name = Idlc::Deploy::Config.get_deployment_var('tfstate_bucket')
  sub_bucket = "#{Idlc::Deploy::Config.get_deployment_var('job_code')}"\
    "#{Idlc::Deploy::Config.get_deployment_var('job')}"\
    "-#{Idlc::Deploy::Config.get_deployment_var('env')}".freeze

  # Pass some ENV vars for Terraform
  Idlc::Deploy::Config.add_deployment_var('environment_key', sub_bucket)
  Idlc::Deploy::Config.add_deployment_var('version', REPO_VERSION)
  Idlc::Deploy::Config.add_deployment_var('major_minor', Idlc::Utility.major_minor(REPO_VERSION))
  Idlc::Deploy::Config.add_deployment_var('major_minor_patch', Idlc::Utility.major_minor_patch(REPO_VERSION))
  Idlc::Deploy::Config.add_deployment_var('build', @config[:server_build])
  Idlc::Deploy::Config.add_deployment_var('app_release', @config[:app_release])

  Idlc::Deploy::Keypair.generate("#{inf_base_dir}/env/kp")
  @workspace.flatten("#{inf_base_dir}/tf", 'tf')
  @workspace.add("#{inf_base_dir}/env/kp")
  @workspace.add('lib/tf/modules')

  config.configure_state(bucket_name, sub_bucket, @workspace.tmp_dir)
end

#deploy_setupv2Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 162

def deploy_setupv2
  Terraform::Binary.configure do |config|
    config.version = SETTINGS['TERRAFORM_VERSION']
    config.download_path = "/tmp/#{SecureRandom.uuid}"
  end

  # Create dynamic variables file for terraform based on config
  keys = {}
  vars_file = ''

   = JSON.parse(open(@config[:config_file]).read)
  ['account', 'environment', 'ec2', 'application'].each do |section|
    [section].each do |key, value|
      # skip dups
      next unless keys[key].nil?

      # replace null with empty string
      value = '' if value.nil?

      # skip lists and maps
      next unless (value.instance_of? String)

      # add to vars file and record key for dups
      keys[key] = 'parsed'
      vars_file += <<~EOH
        variable "#{key}" {}

      EOH

      # load value into envrionment
      Idlc::Deploy::Config.add_deployment_var(key, value)
    end
  end

  # write vars file
  File.open("#{config[:working_dir]}/#{['environment_key']}-tfvars.tf", 'w') { |file| file.write(vars_file) }

  # Pass some extra vars for Terraform
  Idlc::Deploy::Config.add_deployment_var('aws_region', SETTINGS['AWS_REGION'])
  Idlc::Deploy::Config.add_deployment_var('environment_key', ['environment_key'])
  Idlc::Deploy::Config.add_deployment_var('version', ['environment']['inf_version'])
  Idlc::Deploy::Config.add_deployment_var('app_release', @config[:app_release])
  Idlc::Deploy::Config.add_deployment_var('encrypted_svc_pass', ['environment']['encrypted']['svc_pass'])
  ENV['APP_RELEASE'] = @config[:app_release]

  FileUtils.mkdir_p "inf/env/kp"
  Idlc::Deploy::Keypair.generate("inf/env/kp")

  config = Idlc::Deploy::Config.new(SETTINGS['AWS_REGION'])
  config.configure_state(
    ['account']['tfstate_bucket'],
    ['environment_key'],
    @config[:working_dir]
  )
end

#inf_base_dirObject



226
227
228
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 226

def inf_base_dir
  SETTINGS['INF_BASE_DIR']
end

#needs_help?(params) ⇒ Boolean

Returns:

  • (Boolean)


242
243
244
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 242

def needs_help?(params)
  params.include?('-h') || params.include?('--help')
end

#needs_version?(params) ⇒ Boolean

Returns:

  • (Boolean)


246
247
248
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 246

def needs_version?(params)
  params.include?('-v') || params.include?('--version')
end

#run_with_default_options(params = []) ⇒ Object

optparser overwrites -h / –help options with its own. In order to control this behavior, make sure the default options are handled here.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 46

def run_with_default_options(params = [])
  if needs_help?(params)
    msg(opt_parser.to_s)
    0
  elsif needs_version?(params)
    msg("Pfm Version: #{Pfm::VERSION}")
    0
  else
    ENV['DEBUG'] = 'true' if verbose?(params)
    run(params)
  end
rescue NameError => e
  err("ERROR: #{e.message}\n")
  1
rescue OptionParser::InvalidOption, OptionParser::MissingArgument => e
  err("ERROR: #{e.message}\n")
  msg(opt_parser)
  1
rescue Idlc::Build::MissingMetadataFile, Idlc::Build::MissingRequiredMetadataAttribute, InvalidRepository => e
  err("ERROR: #{e.message}\n")
  1
ensure
  @workspace.cleanup unless @workspace.empty?
end

#templates_dirObject



218
219
220
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 218

def templates_dir
  "#{__dir__}/templates/#{@build_metadata.attributes['build_stage'].value}"
end

#verbose?(params) ⇒ Boolean

Returns:

  • (Boolean)


250
251
252
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 250

def verbose?(params)
  params.include?('-V') || params.include?('--verbose')
end