Class: Lono::Cfn::Base

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Includes:
AwsServices, Blueprint::Root, Suffix, Util, Lono::Conventions
Defined in:
lib/lono/cfn/base.rb

Constant Summary collapse

@@generate_all =

Use class variable to cache this only runs once across all classes. base.rb, diff.rb, preview.rb

nil

Instance Method Summary collapse

Methods included from Util

#are_you_sure?, #switch_current

Methods included from Suffix

#allow_suffix?, #append_suffix, #random_suffix, #remove_suffix, #stack_name_suffix

Methods included from Lono::Conventions

#template_param_convention

Methods included from Blueprint::Root

#bundler_groups, #find_blueprint_root, #require_bundle_gems, #set_blueprint_root

Methods included from AwsServices

#cfn, #ec2, #iam, #s3, #s3_presigner, #s3_resource, #sts

Methods included from AwsServices::Util

#find_stack, #rollback_complete?, #stack_exists?, #testing_update?

Constructor Details

#initialize(stack_name, options = {}) ⇒ Base

Returns a new instance of Base.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/lono/cfn/base.rb', line 12

def initialize(stack_name, options={})
  @options = options # options must be set first because @option used in append_suffix

  stack_name = switch_current(stack_name)
  @stack_name = append_suffix(stack_name)
  Lono::ProjectChecker.check

  @blueprint = options[:blueprint] || remove_suffix(@stack_name)
  @template, @param = template_param_convention(options)

  set_blueprint_root(@blueprint)

  @template_path = "#{Lono.config.output_path}/#{@blueprint}/templates/#{@template}.yml"
end

Instance Method Details

#build_filesObject



163
164
165
# File 'lib/lono/cfn/base.rb', line 163

def build_files
  Lono::AppFile::Build.new(@blueprint, @options).run
end

#build_scriptsObject



159
160
161
# File 'lib/lono/cfn/base.rb', line 159

def build_scripts
  Lono::Script::Build.new(@blueprint, @options).run
end

#capabilitiesObject



261
262
263
264
265
266
# File 'lib/lono/cfn/base.rb', line 261

def capabilities
  return @options[:capabilities] if @options[:capabilities]
  if @options[:sure] || @options[:iam]
    ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"]
  end
end

#check_filesObject



228
229
230
231
232
233
234
# File 'lib/lono/cfn/base.rb', line 228

def check_files
  errors = []
  unless File.exist?(@template_path)
    errors << "Template file missing: could not find #{@template_path}"
  end
  errors
end

#check_for_errorsObject



219
220
221
222
223
224
225
226
# File 'lib/lono/cfn/base.rb', line 219

def check_for_errors
  errors = check_files
  unless errors.empty?
    puts "Please double check the command you ran.  There were some errors."
    puts "ERROR: #{errors.join("\n")}".color(:red)
    exit
  end
end

#command_with_iam(capabilities) ⇒ Object



120
121
122
# File 'lib/lono/cfn/base.rb', line 120

def command_with_iam(capabilities)
  "#{File.basename($0)} #{ARGV.join(' ')} --capabilities #{capabilities}"
end

#continue_update_rollbackObject



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/lono/cfn/base.rb', line 76

def continue_update_rollback
  continue_update_rollback_sure?
  params = {stack_name: @stack_name}
  show_parameters(params, "cfn.continue_update_rollback")
  begin
    cfn.continue_update_rollback(params)
  rescue Aws::CloudFormation::Errors::ValidationError => e
    puts "ERROR5: #{e.message}".red
    exit 1
  end
end

#continue_update_rollback_sure?Boolean

Returns:

  • (Boolean)


63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/lono/cfn/base.rb', line 63

def continue_update_rollback_sure?
  puts <<~EOL
    The stack is in the UPDATE_ROLLBACK_FAILED state. More info here: https://amzn.to/2IiEjc5
    Would you like to try to continue the update rollback? (y/N)
  EOL

  sure = @options[:sure] ? "y" : $stdin.gets
  unless sure =~ /^y/
    puts "Exiting without continuing the update rollback."
    exit 0
  end
end

#delete_rollback_stackObject



88
89
90
91
# File 'lib/lono/cfn/base.rb', line 88

def delete_rollback_stack
  rollback = Rollback.new(@stack_name)
  rollback.delete_stack
end

#ensure_s3_bucket_existObject



153
154
155
156
157
# File 'lib/lono/cfn/base.rb', line 153

def ensure_s3_bucket_exist
  bucket = Lono::S3::Bucket.new
  return if bucket.exist?
  bucket.deploy
end

#exit_unless_updatable!(status) ⇒ Object



246
247
248
249
250
251
252
253
254
# File 'lib/lono/cfn/base.rb', line 246

def exit_unless_updatable!(status)
  return true if testing_update?
  return false if @options[:noop]

  unless status =~ /_COMPLETE$/ || status == "UPDATE_ROLLBACK_FAILED"
    puts "Cannot create a change set for the stack because the #{@stack_name} is not in an updatable state.  Stack status: #{status}".color(:red)
    quit(1)
  end
end

#generate_allObject



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
# File 'lib/lono/cfn/base.rb', line 126

def generate_all
  return @@generate_all if @@generate_all

  if @options[:lono]
    ensure_s3_bucket_exist

    build_scripts
    generate_templates # generates with some placeholders for build_files IE: file://app/files/my.rb
    build_files # builds app/files to output/BLUEPRINT/files

    post_process_templates

    unless @options[:noop]
      upload_files
      upload_scripts
      upload_templates
    end
  end

  # Pass down all options to generate_params because it eventually uses template
  param_generator.generate  # Writes the json file in CamelCase keys format
  @@generate_all = param_generator.params    # Returns Array in underscore keys format

  check_for_errors
  @@generate_all
end

#generate_templatesObject



167
168
169
# File 'lib/lono/cfn/base.rb', line 167

def generate_templates
  Lono::Template::Generator.new(@blueprint, @options.merge(stack: @stack_name)).run
end

#param_generatorObject



171
172
173
174
175
176
177
178
# File 'lib/lono/cfn/base.rb', line 171

def param_generator
  generator_options = {
    regenerate: true,
    allow_not_exists: true,
  }.merge(@options)
  generator_options[:stack] ||= @stack_name || @blueprint
  Lono::Param::Generator.new(@blueprint, generator_options)
end

#post_process_templatesObject



181
182
183
# File 'lib/lono/cfn/base.rb', line 181

def post_process_templates
  Lono::Template::PostProcessor.new(@blueprint, @options).run
end

#pretty_path(path) ⇒ Object



291
292
293
# File 'lib/lono/cfn/base.rb', line 291

def pretty_path(path)
  path.sub("#{Lono.root}/",'')
end

#prompt_for_iam(capabilities) ⇒ Object



112
113
114
115
116
117
118
# File 'lib/lono/cfn/base.rb', line 112

def prompt_for_iam(capabilities)
  puts "This stack will create IAM resources.  Please approve to run the command again with #{capabilities} capabilities."
  puts "  #{command_with_iam(capabilities)}"

  puts "Please confirm (y/N)"
  $stdin.gets
end

#quit(signal) ⇒ Object

To allow mocking in specs



257
258
259
# File 'lib/lono/cfn/base.rb', line 257

def quit(signal)
  exit signal
end

#rerun_with_iam?(e) ⇒ Boolean

Returns:

  • (Boolean)


97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/lono/cfn/base.rb', line 97

def rerun_with_iam?(e)
  # e.message is "Requires capabilities : [CAPABILITY_IAM]"
  # grab CAPABILITY_IAM with regexp
  capabilities = e.message.match(/\[(.*)\]/)[1]
  confirm = prompt_for_iam(capabilities)
  if confirm =~ /^y/
    @options.merge!(capabilities: [capabilities])
    puts "Re-running: #{command_with_iam(capabilities).color(:green)}"
    true
  else
    puts "Exited"
    exit 1
  end
end

#runObject



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
58
59
60
61
# File 'lib/lono/cfn/base.rb', line 32

def run
  starting_message
  params = generate_all
  begin
    save_stack(params) # defined in the sub class
  rescue Aws::CloudFormation::Errors::InsufficientCapabilitiesException => e
    yes = rerun_with_iam?(e)
    retry if yes
  rescue Aws::CloudFormation::Errors::ValidationError => e
    if e.message.include?("No updates") # No updates are to be performed.
      puts "WARN: #{e.message}".color(:yellow)
    elsif e.message.include?("UPDATE_ROLLBACK_FAILED") # https://amzn.to/2IiEjc5
      continue_update_rollback
    else
      puts "ERROR: #{e.message}".color(:red)
      exit 1
    end
  end

  return unless @options[:wait]

  success = false
  if !@options[:noop]
    success = status.wait
  end

  # exit code for cfn.rb cli, so there's less duplication
  exit 1 unless success
  success
end

#set_template_body!(params) ⇒ Object

Lono always uploads the template to s3 so we can use much larger templates.

template_body: 51,200 bytes - filesystem limit
template_url: 460,800 bytes - s3 limit

Reference: docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html



283
284
285
286
287
288
289
# File 'lib/lono/cfn/base.rb', line 283

def set_template_body!(params)
  upload = Lono::Template::Upload.new(@blueprint)
  url_path = @template_path.sub("#{Lono.root}/",'')
  url = upload.s3_presigned_url(url_path)
  params[:template_url] = url
  params
end

#show_parameters(params, meth = nil) ⇒ Object



268
269
270
271
272
273
274
275
# File 'lib/lono/cfn/base.rb', line 268

def show_parameters(params, meth=nil)
  params = params.clone.compact
  params[:template_body] = "Hidden due to size... View at: #{pretty_path(@template_path)}"
  params[:template_url] = params[:template_url].sub(/\?.*/,'')
  to = meth || "AWS API"
  puts "Parameters passed to #{to}:"
  puts YAML.dump(params.deep_stringify_keys)
end

#stack_status(stack_name) ⇒ Object



238
239
240
241
242
243
244
# File 'lib/lono/cfn/base.rb', line 238

def stack_status(stack_name)
  return true if testing_update?
  return false if @options[:noop]

  resp = cfn.describe_stacks(stack_name: stack_name)
  resp.stacks[0].stack_status
end

#starting_messageObject



27
28
29
30
# File 'lib/lono/cfn/base.rb', line 27

def starting_message
  action = self.class.to_s.split('::').last
  puts "#{action} #{@stack_name.color(:green)} stack..."
end

#statusObject



93
94
95
# File 'lib/lono/cfn/base.rb', line 93

def status
  @status ||= Status.new(@stack_name)
end

#tagsObject

Maps to CloudFormation format. Example:

{"a"=>"1", "b"=>"2"}

To

[{key: "a", value: "1"}, {key: "b", value: "2"}]


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/lono/cfn/base.rb', line 203

def tags
  tags = @options[:tags] || []
  tags = tags.map do |k,v|
    { key: k, value: v }
  end

  update_operation = %w[Preview Update].include?(self.class.to_s)
  if tags.empty? && update_operation
    resp = cfn.describe_stacks(stack_name: @stack_name)
    tags = resp.stacks.first.tags
    tags = tags.map(&:to_h)
  end

  tags
end

#upload_filesObject



193
194
195
# File 'lib/lono/cfn/base.rb', line 193

def upload_files
  Lono::AppFile::Upload.new(@blueprint).upload
end

#upload_scriptsObject



189
190
191
# File 'lib/lono/cfn/base.rb', line 189

def upload_scripts
  Lono::Script::Upload.new(@blueprint).run
end

#upload_templatesObject



185
186
187
# File 'lib/lono/cfn/base.rb', line 185

def upload_templates
  Lono::Template::Upload.new(@blueprint).run
end