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.



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

def initialize
  super

  @workspace = Idlc::Workspace.new
end

Instance Method Details

#build_base_dirObject



254
255
256
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 254

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

#build_dirObject



262
263
264
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 262

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

#build_exists?Boolean

Returns:

  • (Boolean)


266
267
268
269
270
271
272
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 266

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



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
115
116
117
118
119
120
121
122
123
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 80

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
   = Idlc::Build::.new(@params.first, @config[:build_metadata])

  # load the rest of the metadata
  .load

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

  # check metadata requirements
  .requirements_satisfied?

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

  .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(
    .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:



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
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 125

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])

  FileUtils.mkdir_p "inf/env/kp"
  download_private_key(bucket_name, sub_bucket, "#{inf_base_dir}/env/kp")
  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



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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 173

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|
      next unless keys[key].nil?

      value = '' if value.nil?

      keys[key] = 'parsed'
      key_values = []
      if section == "environment" and key == "email"
        value.each do |email_key, email_value|
          email_value = '' if email_value.nil?
          key_values << ["email_" + email_key, email_value]
        end
      else
        next unless (value.instance_of? String)
        key_values << [key, value]
      end
      key_values.each do |kv|
        # add to vars file and record key for dups
        unless upgraded_terraform?
          vars_file += "            variable \"\#{kv[0]}\" {}\n\n          EOH\n        end\n\n        # load value into envrionment\n        Idlc::Deploy::Config.add_deployment_var(kv[0], kv[1])\n      end\n    end\n  end\n\n  # write vars file\n  unless upgraded_terraform?\n    File.open(\"\#{config[:working_dir]}/\#{env_metadata['environment_key']}-tfvars.tf\", 'w') { |file| file.write(vars_file) }\n  end\n\n  # Pass some extra vars for Terraform\n  Idlc::Deploy::Config.add_deployment_var('aws_region', SETTINGS['AWS_REGION'])\n  Idlc::Deploy::Config.add_deployment_var('environment_key', env_metadata['environment_key'])\n  Idlc::Deploy::Config.add_deployment_var('version', env_metadata['environment']['inf_version'])\n  Idlc::Deploy::Config.add_deployment_var('app_release', @config[:app_release])\n  Idlc::Deploy::Config.add_deployment_var('encrypted_svc_pass', env_metadata['environment']['encrypted']['svc_pass'])\n  ENV['APP_RELEASE'] = @config[:app_release]\n\n  FileUtils.mkdir_p \"inf/env/kp\"\n  download_private_key(env_metadata['account']['tfstate_bucket'], env_metadata['environment_key'], \"inf/env/kp\")\n  Idlc::Deploy::Keypair.generate(\"inf/env/kp\")\n  if upgraded_terraform?\n    FileUtils.ln_sf(\"../inf\", \"package-infra/inf\")\n    FileUtils.ln_sf(\"../terraform.auto.tfvars\", \"package-infra/svc_pass.auto.tfvars\")\n  end\n\n  config = Idlc::Deploy::Config.new(SETTINGS['AWS_REGION'])\n  config.configure_state(\n    env_metadata['account']['tfstate_bucket'],\n    env_metadata['environment_key'],\n    @config[:working_dir]\n  )\nend\n"

#download_private_key(bucket, subkey, outdir) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 72

def download_private_key(bucket, subkey, outdir)
  s3 = Aws::S3::Client.new(region: SETTINGS['AWS_REGION'])
  resp = s3.get_object(bucket: bucket, key: "#{subkey}/private_key.pem", response_target: "#{outdir}/private_key.pem")
  true
rescue Aws::S3::Errors::NoSuchKey
  false
end

#inf_base_dirObject



258
259
260
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 258

def inf_base_dir
  SETTINGS['INF_BASE_DIR']
end

#needs_help?(params) ⇒ Boolean

Returns:

  • (Boolean)


274
275
276
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 274

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

#needs_version?(params) ⇒ Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 278

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.



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/iapi-idlc-sdk-pfm/command/base.rb', line 47

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



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

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

#upgraded_terraform?Boolean

Returns:

  • (Boolean)


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

def upgraded_terraform?
  major_version = Terraform::Binary.config.version.split(".")[0]
  major_version.to_i > 0
end

#verbose?(params) ⇒ Boolean

Returns:

  • (Boolean)


282
283
284
# File 'lib/iapi-idlc-sdk-pfm/command/base.rb', line 282

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