Class: AppCommand::CloudFormationCreate

Inherits:
Convoy::ActionCommand::Base
  • Object
show all
Defined in:
lib/routes/cloudformation_create.rb

Constant Summary collapse

DEFAULT =
'Default'
PARAMETERS =
'Parameters'
SPECIAL_METHODS =
[:before_create, :after_create, :before_teardown, :after_teardown]
AWS_TAGS =
%w(Environment Project Region Category Template)
RESERVED_WORDS =
%w(cache_uuid category description environment owner project projectid region resource stack stackname template terminationprotection timeout)
OPTION_PROJECT_ID =
'ProjectId'
OPTION_STACK_ID =
'StackId'
OPTION_STACK_NAME =
'StackName'
OPTION_TIMEOUT =
'Timeout'
OPTION_DESCRIPTION =
'Description'
OPTION_PROJECT =
'Project'
OPTION_ENVIRONMENT =
'Environment'
OPTION_REGION =
'Region'
OPTION_CATEGORY =
'Category'
OPTION_TEMPLATE =
'Template'
OPTION_TERM_PROTECT =
'TerminationProtection'
OPTION_OWNER =
'Owner'
MATCHERS =
%w(CATEGORY TEMPLATE PROJECT ENVIRONMENT REGION UUID)
OPTIONS =
'Options'
SPECIAL =
'AWS-specific'
CACHE_UUID =
'cache_uuid'
TEST =
'test'
SPACER =
'<<--Spacer-->>'
CAPABILITIES =
'Capabilities'
RETURN_VALUE =
'PjNkHK33EopWxCpzOQfuku3la'
SYSTEM =
'System'
NESTED =
'nested'
STACK =
'Stack'

Instance Method Summary collapse

Instance Method Details

#executeObject



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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/routes/cloudformation_create.rb', line 37

def execute

    begin

        @opts = command_options
        @args = arguments

        @template        = nil
        @templates       = {}
        @params          = {}
        @params_system   = nil
        @output          = {}
        @regions         = App::AWSCli::get_regions
        @lookups         = {}
        @lookup_cache    = {}
        @data            = nil
        @table_widths    = {}
        @export_map      = {}
        @columns         = {}
        @options_default = {}
        @cache           = {}
        @cache_valid     = false
        @projects        = {}
        @nested_stacks   = {}

        @terminal_width                             = Blufin::Terminal::get_terminal_width
        @columns, @data, @export_map, @table_widths = App::AWSReports::(@regions)

        @owner = Blufin::Config::get['DeveloperName']

        Blufin::Projects::init(App::AWSProfile::get_profile['Projects'])

        opts_validate
        opts_routing

    rescue => e

        Blufin::Terminal::print_exception(e)

    end

end

#opts_routingObject

Raises:

  • (RuntimeError)


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/routes/cloudformation_create.rb', line 392

def opts_routing

    used_cache                    = true
    showing_tags                  = false

    # Show prompt to select template.
    category, template, @template = select_template_prompt

    # Will be something like: "ec2/build-server"
    template_name                 = "#{category}/#{template}"

    if @params.any?
        # Here we replace the UUID for the stack-name at the last-second to enable parallel, identical runs (if exists).
        @params[OPTION_STACK_NAME] = replace_stack_suffix(@params[OPTION_STACK_NAME]) if @params.has_key?(OPTION_STACK_NAME)
    else
        used_cache = false
        if !@template[:parameters].nil? && @template[:parameters].any?
            @template[:parameters].each_with_index do |(param_name, param_data), idx|
                if AWS_TAGS.include?(param_name) && !showing_tags
                    showing_tags = true
                    puts "\x1B[38;5;#{App::AWSOutputter::DIVIDER_COLOR}m--- \x1B[38;5;136m[Tags]\x1B[0m\x1B[38;5;#{App::AWSOutputter::DIVIDER_COLOR}m #{'-' * (@terminal_width - 17)}\x1B[0m"
                    puts
                end

                # TODO NOW - REMOVE:STACK_ID - This needs to be re-instated once we have the stacks.yml parsing.
                # Deployment ID needs to be handled here because we need to know what the project/region/environment is before we can display the options.
                # if param_name == OPTION_PROJECT_ID
                #     # Figure out which deployments are eligible for this stack.
                #     if @template.has_key?(:stack_id)
                #         @projects = Blufin::Projects::get_deployments(
                #             @params[OPTION_PROJECT],
                #             @template[:stack_id],
                #             @params[OPTION_REGION],
                #             @params[OPTION_ENVIRONMENT]
                #         )
                #         if @projects.any?
                #             project_options = []
                #             @projects.each { |project| project_options << project[1][Blufin::Projects::PROJECT_ID] }
                #             @params[param_name] = Blufin::Terminal::prompt_select('Select Project ID:', project_options, help: param_data[OPTION_DESCRIPTION])
                #             puts
                #         end
                #     end
                #     next
                # end

                @params[param_name] = get_parameter_value(param_data, param_name, category, template)
                # Puts space unless it's a hidden parameter. Keeps spacing consistent.
                puts unless [OPTION_TIMEOUT].include?(param_name)
            end
        end
        @params[OPTION_CATEGORY] = category
        @params[OPTION_TEMPLATE] = template
        # Cache the inputted value(s).
        cache_params             = @params
        cache_params[CACHE_UUID] = get_cache_hexdigest(@template[:parameters])
        Blufin::Files::write_file(get_cache_file(category, template), [cache_params.to_json])
    end

    # If this is a test-run, abandon ship here.
    if @opts[:test]
        puts if used_cache
        puts "\x1B[38;5;196m  Exiting because this is only a test-run.\x1B[0m"
        puts
        puts "\x1B[38;5;246m#{@params.to_yaml}\x1B[0m"
        exit
    end

    system('clear')

    capabilities_arr = []
    capabilities_str = nil

    # # TODO - REMOVE OR EMBED? This shows all the params eligible for replacing...
    # puts get_replacer_params(category, template).to_yaml
    # exit

    # Replace matchers in CloudFormation Template before uploading to S3.
    replacer_params  = get_replacer_params(category, template)

    if !@nested_stacks[template_name].nil? && @nested_stacks[template_name].any?
        # First create a temporary filename map for all the stacks we need to upload.
        tmp_filenames = {}
        @nested_stacks[template_name].keys.each do |stack|
            tmp_filenames[stack] = "#{stack.gsub('/', '-')}-#{DateTime.now.strftime('%Y%m%d-%H%M%S')}.yml"
        end

        replacer_params[STACK] = {}
        @nested_stacks[template_name].each do |stack|
            replacer_params[STACK][stack[0]] = {
                :s3_url => "#{App::AWSCloudFormation::get_s3_bucket_url}/#{tmp_filenames[stack[0]]}"
            }
        end

        # Upload Nested Stacks to S3.
        @nested_stacks[template_name].each do |stack|
            nested_template_converted = "/tmp/#{tmp_filenames[stack[0]]}"
            nested_template_file      = File.expand_path("#{App::AWSCloudFormation::get_cloudformation_path}/#{stack[0]}/template.yml")
            file_lines                = App::Replacer::replace_yml(nested_template_file, replacer_params)
            Blufin::Files::write_file(nested_template_converted, file_lines)
            # Upload nested template to S3.
            App::AWSCloudFormation::upload_cloudformation_template(nested_template_converted, category, template, filename_override: tmp_filenames[stack[0]])
            system("rm #{nested_template_converted}")
        end

    end

    base_template_file = File.expand_path("#{App::AWSCloudFormation::get_cloudformation_path}/#{category}/#{template}/template.yml")
    raise RuntimeError, "File does not exist: #{base_template_file}" unless Blufin::Files::file_exists(base_template_file)
    tmp_file            = "/tmp/converted-template-#{Blufin::Strings::random_string(4)}.txt"
    base_template_lines = App::Replacer::replace_yml(base_template_file, replacer_params)
    Blufin::Files::write_file(tmp_file, base_template_lines)

    # Upload the template to S3.
    base_template = App::AWSCloudFormation::upload_cloudformation_template(tmp_file, category, template)
    system("rm #{tmp_file}")

    # Validates the base template.
    validation = App::AWSCli::cloudformation_stack_validate(@params[OPTION_REGION], base_template)

    # Check if validation output is JSON (and output appropriate format).
    begin
        hash = JSON.parse(validation.to_json)
        raise RuntimeError, 'Not a Hash' unless hash.is_a?(Hash)
        Blufin::Terminal::success("AWS says your template is: \x1B[38;5;40mVALID")
        # Output the AWS response in YML format.
        Blufin::Terminal::code_highlight(hash.to_yaml, 'yml', 4)
        # Extract required capabilities (if any).
        if hash.has_key?(CAPABILITIES)
            capabilities_arr = hash[CAPABILITIES]
            capabilities_str = "\"#{capabilities_arr.join('" "')}\""
        end
    rescue
        Blufin::Terminal::error("AWS says your template is: \x1B[38;5;196mINVALID", App::AWSCli::format_cli_error(validation), true)
    end

    output                      = {}
    output[OPTION_STACK_NAME]   = @params[OPTION_STACK_NAME]
    output[OPTION_DESCRIPTION]  = @params[OPTION_DESCRIPTION]
    output[SPACER]              = true

    # TODO NOW - REMOVE:STACK_ID - This needs to be re-instated once we have the stacks.yml parsing.
    # if @template.has_key?(:stack_id) && !@params[OPTION_PROJECT_ID].nil? && @params[OPTION_PROJECT_ID].length > 0
    #     output[OPTION_STACK_ID] = @template[:stack_id]
    #     output[OPTION_PROJECT_ID]       = @params[OPTION_PROJECT_ID]
    # end

    output[OPTION_TIMEOUT]      = @params[OPTION_TIMEOUT]
    output[OPTION_TERM_PROTECT] = @params[OPTION_TERM_PROTECT] unless @template[:single_serve]
    output[CAPABILITIES]        = capabilities_arr.join(', ') unless capabilities_str.nil?

    @params.each do |key, value|
        next if RESERVED_WORDS.include?(key.downcase)
        output[key] = value
    end

    params_output = []
    padding       = output.keys.max_by(&:length).length
    spacer_passed = false
    output.each do |key, value|
        next if [OPTION_STACK_ID, OPTION_PROJECT_ID, OPTION_TIMEOUT, OPTION_TERM_PROTECT, CAPABILITIES].include?(key)
        if key == SPACER
            spacer_passed = true
            next
        end
        if spacer_passed
            params_output << "\x1B[38;5;240m#{key.rjust(padding, ' ')} : \x1B[38;5;28m#{value}"
        else
            params_output << "\x1B[38;5;240m#{key.rjust(padding, ' ')} : \x1B[38;5;28m#{value}"
        end
    end

    if @template.has_key?(:stack_id)
        params_output << "\x1B[38;5;240m#{OPTION_PROJECT_ID.rjust(padding, ' ')} : \x1B[38;5;246m#{output[OPTION_PROJECT_ID]}" if output.has_key?(OPTION_PROJECT_ID)
        params_output << "\x1B[38;5;240m#{OPTION_STACK_ID.rjust(padding, ' ')} : \x1B[38;5;246m#{output[OPTION_STACK_ID]}" if output.has_key?(OPTION_STACK_ID)
    end
    params_output << "\x1B[38;5;240m#{OPTION_TIMEOUT.rjust(padding, ' ')} : \x1B[38;5;246m#{output[OPTION_TIMEOUT]} Minute(s)\x1B[0m"
    params_output << "\x1B[38;5;240m#{OPTION_TERM_PROTECT.rjust(padding, ' ')} : #{output[OPTION_TERM_PROTECT] ? "\x1B[38;5;246mYES\x1B[0m" : "\x1B[38;5;246mNO\x1B[0m"}" unless @template[:single_serve]
    params_output << "\x1B[38;5;240m#{CAPABILITIES.rjust(padding, ' ')} : \x1B[38;5;196m#{output[CAPABILITIES]}" if output.has_key?(CAPABILITIES)

    if Blufin::Terminal::prompt_yes_no("Review: #{App::AWSOutputter::render_selection(category, template)}", params_output, 'Create Stack?', false)

        is_ec2      = `#{App::Opt::get_base_path}/#{App::Opt::OPT_PATH}/shell/ec2-check`.to_s.gsub("\n", '') =~ /yes/i
        term_script = false

        # If no 'after' actions necessary, give option to terminate script early.
        if @template[:method_after_create].nil? && !@template[:single_serve]
            options     = [{:text => "Yes \xe2\x80\x94 Wait.", :value => false}, {:text => 'No', :value => true}]
            help_text   = "Select 'No' to end the script immediately. Status can still be viewed in the AWS console."
            term_script = Blufin::Terminal::prompt_select('Wait for stack to build?', options, help: help_text)
            puts
        end

        # Call :before_create() -- if exists.
        @template[:method_before_create].call(@params) unless @template[:method_before_create].nil?

        # TODO - Uncomment to see template (or remove).
        # # Output the base template to terminal (for reference). Nested stacks are currently not outputted.
        # base_template_lines.each do |line|
        #     puts "  \x1B[38;5;240m#{line}\x1B[0m"
        # end
        # puts

        # Create the Stack (if term_scrip == TRUE, script terminates inside).
        App::AWSCli::cloudformation_stack_create(@params[OPTION_REGION], @params[OPTION_STACK_NAME], base_template,
                                                 params:       assemble_params(@params),
                                                 tags:         assemble_tags(@params),
                                                 capabilities: capabilities_arr,
                                                 term_protect: @template[:single_serve] ? false : @params[OPTION_TERM_PROTECT],
                                                 term_script:  term_script,
                                                 timeout:      @params[OPTION_TIMEOUT],
                                                 open_chrome:  !is_ec2)

        # Call :after_create() -- if exists.
        @template[:method_after_create].call(@params) unless @template[:method_after_create].nil?

        # Success/Failure messages.
        if @template[:single_serve]
            if App::AWSCli::execute_as_proc("Deleting Stack: #{Blufin::Terminal::format_highlight(@params[OPTION_STACK_NAME])}", "cloudformation delete-stack --stack-name #{@params[OPTION_STACK_NAME]}", @params[OPTION_REGION])
                Blufin::Terminal::success("#{App::AWSOutputter::render_selection(category, template)} was successfully created (and stack removed).") unless term_script
            else
                Blufin::Terminal::error('Something went wrong.')
            end
        else
            Blufin::Terminal::success('Stack creation was successful.', nil, false) unless term_script
        end
    end
end

#opts_validateObject



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
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
161
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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/routes/cloudformation_create.rb', line 80

def opts_validate

    # Windows is currently not supported, so bomb-out.
    Blufin::Tools::os_not_supported([Blufin::Tools::OS_WINDOWS])

    # If clear-cache flag is set, removed all cached stuff.
    if @opts[:clear_cache]
        # Clear out the SSH keys (cached from S3).
        App::AWSProfile::download_s3_ssh_users(false)
    end

    # If Terminal window is smaller than 230, bomb-out.
    terminal_width_actual   = Blufin::Terminal::get_terminal_width
    terminal_required_width = 227
    Blufin::Terminal::error("Output for this command \x1B[38;5;240m(#{Blufin::Terminal::format_action(terminal_required_width)}\x1B[38;5;240m-width)\x1B[0m does not fit in Terminal \x1B[38;5;240m(#{Blufin::Terminal::format_action(terminal_width_actual)}\x1B[38;5;240m-width)\x1B[0m", 'Please make your terminal wider and try again.', true) if terminal_width_actual < terminal_required_width

    @warnings                            = []
    @lookups                             = App::AWSReports::get_lookups(@data)

    # Add SSH Users to Lookups (if they've been configured).
    users                                = App::AWSProfile::get_ssh_users
    @lookups[App::Replacer::SSH_USERS]   = users if users.any?

    # TODO - Environments cannot be hard-coded here. Possibly get from deployments (once we have it parsing)?
    @options_default[OPTION_ENVIRONMENT] = %w(dev test staging prod)
    @options_default[OPTION_REGION]      = App::AWSProfile::get_profile[App::AWSProfile::CLOUDFORMATION]['Defaults']['Regions']
    @options_default[OPTION_STACK_NAME]  = App::AWSProfile::get_profile[App::AWSProfile::CLOUDFORMATION]['Defaults']['StackName']
    @options_default[OPTION_TIMEOUT]     = App::AWSProfile::get_profile[App::AWSProfile::CLOUDFORMATION]['Defaults']['Timeout']
    @options_default[OPTION_PROJECT]     = Blufin::Projects::get_project_names

    # Loop the entire blufin-secrets/cloudformation path(s) and validate all the template(s).
    Blufin::Files::get_dirs_in_dir(App::AWSCloudFormation::get_cloudformation_path).each do |path|
        ps               = path.split('/')
        category         = ps[ps.length - 1]
        template_folders = Blufin::Files::get_dirs_in_dir(path)
        template_folders.each do |path_inner|
            ps                     = path_inner.split('/')
            template               = ps[ps.length - 1]
            template_name          = "#{category}/#{template}"
            template_path          = nil
            file_cloudformation    = nil
            file_ruby              = nil
            method_before_create   = nil
            method_after_create    = nil
            method_before_teardown = nil
            method_after_teardown  = nil
            intro                  = nil
            description            = nil
            stack_name             = nil
            projects               = nil
            environments           = nil
            regions                = nil
            timeout                = nil
            single_serve           = false
            stack_id               = nil
            parameters             = {}
            parameters_no_sort     = nil
            warnings_count         = @warnings.length
            raise RuntimeError, "Template name must consist of [service]/[service-description] with exactly one slash, instead got: #{template_name}" if template_name.strip.split('/').length != 2
            Blufin::Files::get_files_in_dir(path_inner).each do |file|
                filename      = Blufin::Files::extract_file_name(file)
                template_path = Blufin::Files::extract_path_name(file)
                if filename == 'template.yml'
                    begin
                        yml_data = YAML.load_file(File.expand_path(file))
                    rescue Exception => e
                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 #{e.message.split('template.yml): ')[1].capitalize}"
                        next
                    end
                    if yml_data.is_a?(Hash)
                        file_cloudformation = file
                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 AWSTemplateFormatVersion: '2010-09-09' is missing." unless yml_data.has_key?('AWSTemplateFormatVersion')
                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 This template either has no resources, invalid resources, or something else wrong with the resources." if !yml_data.has_key?('Resources') || yml_data['Resources'].nil? || !yml_data['Resources'].is_a?(Hash) || yml_data['Resources'].length == 0
                        if yml_data.has_key?(PARAMETERS) && yml_data[PARAMETERS].is_a?(Hash) && yml_data[PARAMETERS].length > 0
                            yml_data[PARAMETERS].each do |param_name, param_data|
                                # Validate keys are in specific order.
                                expected = {
                                    'Type'                  => true,
                                    'Description'           => false,
                                    'Default'               => false,
                                    'AllowedValues'         => false,
                                    'AllowedPattern'        => false,
                                    'MinLength'             => false,
                                    'MinValue'              => false,
                                    'MaxLength'             => false,
                                    'MaxValue'              => false,
                                    'ConstraintDescription' => false,
                                    'NoEcho'                => false,
                                }
                                Blufin::Validate::assert_valid_keys(expected, param_data.keys, "#{file} \xe2\x86\x92 #{param_name}")
                                @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Template has reserved parameter: #{Blufin::Terminal::format_invalid(param_name)}" if [OPTION_STACK_NAME.downcase].concat(RESERVED_WORDS).include?(param_name.downcase)
                                parameters[param_name] = param_data
                                if @lookups.has_key?(param_name)
                                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Parameter: #{param_name} cannot have default value: '#{param_data[DEFAULT]}' because it is a live look-up list (from AWS)." if param_data.keys.include?(DEFAULT)
                                end
                                # Validate parameter type.
                                valid_parameter_types   = %w(String Number List<Number> CommaDelimitedList)
                                valid_parameter_regexes = [/^AWS::[A-Za-z0-9]+::[A-Za-z0-9]+::[A-Za-z0-9]+$/, /^List<AWS::[A-Za-z0-9]+::[A-Za-z0-9]+::[A-Za-z0-9]+>$/]
                                unless valid_parameter_types.include?(param_data['Type'])
                                    matches_vpr = false
                                    valid_parameter_regexes.each do |vpr|
                                        matches_vpr = true if param_data['Type'] =~ vpr
                                    end
                                    if matches_vpr
                                        constraints = []
                                        constraints << 'AllowedPattern' if param_data.has_key?('AllowedPattern')
                                        constraints << 'MinLength' if param_data.has_key?('MinLength')
                                        constraints << 'MaxLength' if param_data.has_key?('MaxLength')
                                        constraints << 'MinValue' if param_data.has_key?('MinValue')
                                        constraints << 'MaxValue' if param_data.has_key?('MaxValue')
                                        if constraints.any?
                                            @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid parameter constraint(s): #{Blufin::Terminal::format_invalid(constraints.join(','))}. These don't apply to AWS-Specific parameters."
                                        end
                                    else
                                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid parameter type: #{Blufin::Terminal::format_invalid(param_data['Type'])}"
                                    end
                                end
                                # Can only have Max/MinLength if this is a String.
                                if param_data.has_key?('MinLength') || param_data.has_key?('MaxLength') || param_data.has_key?('AllowedPattern')
                                    unless param_data['Type'] == 'String'
                                        constraints = []
                                        constraints << 'MinLength' if param_data.has_key?('MinLength')
                                        constraints << 'MaxLength' if param_data.has_key?('MaxLength')
                                        constraints << 'AllowedPattern' if param_data.has_key?('AllowedPattern')
                                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid parameter constraint(s): #{Blufin::Terminal::format_invalid(constraints.join(','))}. To use these, type must be String."
                                    end
                                end
                                # Can only have Max/MinValue if this is a Number.
                                if param_data.has_key?('MinValue') || param_data.has_key?('MaxValue')
                                    unless param_data['Type'] == 'Number'
                                        constraints = []
                                        constraints << 'MinValue' if param_data.has_key?('MinValue')
                                        constraints << 'MaxValue' if param_data.has_key?('MaxValue')
                                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid parameter constraint(s): #{Blufin::Terminal::format_invalid(constraints.join(','))}. To use these, type must be Number."
                                    end
                                end
                                # If Allowed Values is set, certain conditions must apply.
                                if param_data.has_key?('AllowedValues')
                                    %w(AllowedPattern MinLength MaxLength MinValue MaxValue).each do |invalid_key|
                                        if param_data.has_key?(invalid_key)
                                            @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 AllowedValues is set so cannot have: #{Blufin::Terminal::format_invalid(param_data['invalid_key'])}"
                                        end
                                    end
                                    # Must be Array.
                                    unless param_data['AllowedValues'].is_a?(Array)
                                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 AllowedValues must be Array, instead got: #{Blufin::Terminal::format_invalid(param_data['AllowedValues'].class)}"
                                    end
                                end
                            end
                        end
                        # Validate description (if exists).
                        if yml_data.has_key?(OPTION_DESCRIPTION)
                            description = yml_data[OPTION_DESCRIPTION]
                        else
                            @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Template is missing description."
                        end
                        # Look for (and validate) DeletionPolicy: Retain
                        if yml_data.has_key?('Resources') && yml_data['Resources'].is_a?(Hash)
                            key_has_dp = {}
                            yml_data['Resources'].keys { |k| key_has_dp[k] = 0 }
                            yml_data['Resources'].each do |key, value|
                                key_has_dp[key] = 1 if value.is_a?(Hash) && value.has_key?('DeletionPolicy') && value['DeletionPolicy'].downcase == 'retain'
                            end
                            key_has_dp_sum = 0
                            key_has_dp.each { |k, v| key_has_dp_sum += v }
                            if key_has_dp_sum == 0 || key_has_dp_sum == yml_data['Resources'].keys.length
                                # If we have at least 1 DeletionPolicy: Retain and no errors, this is a single-serve template.
                                single_serve = key_has_dp_sum > 0
                            else
                                # Add a warning if not all resources have the DeletionPolicy: Retain.
                                @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 If DeletionPolicy: Retain is used, it must be set on all resources for template."
                            end
                        end
                    end
                elsif filename == 'template.rb'
                    file_ruby = file
                    # Load the template.rb file/class.
                    require file
                    expected_constants = %w()
                    Template::constants.each do |constant|
                        constant = constant.to_s
                        expected_constants.delete(constant) if expected_constants.include?(constant)
                        # Optional constants.
                        intro              = Template::INTRO if constant == 'INTRO'
                        stack_name         = Template::STACK_NAME if constant == 'STACK_NAME'
                        projects           = Template::PROJECTS if constant == 'PROJECTS'
                        environments       = Template::ENVIRONMENTS if constant == 'ENVIRONMENTS'
                        regions            = Template::REGIONS if constant == 'REGIONS'
                        timeout            = Template::TIMEOUT if constant == 'TIMEOUT'
                        stack_id           = Template::STACK_ID if constant == 'STACK_ID'
                        parameters_no_sort = Template::PARAMETERS_NO_SORT if constant == 'PARAMETERS_NO_SORT'
                    end
                    # Validate stack name.
                    if stack_name.nil? || stack_name.strip == ''
                        stack_name = @options_default[OPTION_STACK_NAME]
                    end
                    results = App::Replacer::scan_string(stack_name)
                    validate_matchers(file_cloudformation, results, template_name, parameters)
                    # Make sure deployment stack is not a reserved word.
                    if stack_id.is_a?(String) && %w(lambda).include?(stack_id.downcase)
                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 #{Blufin::Terminal::format_highlight('STACK_ID')} value is a reserved word: #{Blufin::Terminal::format_invalid(stack_id)}"
                    end
                    # If any constants are missing, this should catch it.
                    expected_constants.each { |missing_constant| @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 The #{Blufin::Terminal::format_highlight('template.rb')}\x1B[38;5;240m file is missing a constant: #{Blufin::Terminal::format_invalid(missing_constant)}" }
                    Template::methods.each do |method|
                        if SPECIAL_METHODS.include?(method)
                            if method == :before_create
                                method_params = Template::method(:before_create).parameters
                                if method_params == [[:req, :params]]
                                    method_before_create = Template::method(:before_create)
                                else
                                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid #{Blufin::Terminal::format_highlight(':before_create')}\x1B[38;5;240m parameters: #{Blufin::Terminal::format_invalid(method_params.inspect)}"
                                end
                            end
                            if method == :after_create
                                method_params = Template::method(:after_create).parameters
                                if method_params == [[:req, :params], [:req, :output]]
                                    method_after_create = Template::method(:after_create)
                                else
                                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid #{Blufin::Terminal::format_highlight(':after_create')}\x1B[38;5;240m parameters: #{Blufin::Terminal::format_invalid(method_params.inspect)}"
                                end
                            end
                            if method == :before_teardown
                                method_params = Template::method(:before_teardown).parameters
                                if method_params == [[:req, :output]]
                                    method_before_teardown = Template::method(:before_teardown)
                                else
                                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid #{Blufin::Terminal::format_highlight(':before_teardown')}\x1B[38;5;240m parameters: #{Blufin::Terminal::format_invalid(method_params.inspect)}"
                                end
                            end
                            if method == :after_teardown
                                method_params = Template::method(:after_teardown).parameters
                                if method_params == [[:req, :output]]
                                    method_after_teardown = Template::method(:after_teardown)
                                else
                                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Invalid #{Blufin::Terminal::format_highlight(':after_teardown')}\x1B[38;5;240m parameters: #{Blufin::Terminal::format_invalid(method_params.inspect)}"
                                end
                            end
                        end
                    end
                    intro       = nil if !intro.nil? && intro.gsub("\n", '').gsub("\t", '').strip == ''
                    stack_name  = nil if !stack_name.nil? && stack_name.gsub("\n", '').gsub("\t", '').strip == ''
                    description = nil if !description.nil? && description.gsub("\n", '').gsub("\t", '').strip == ''
                    # Unload the template.rb file/class.
                    Object.send(:remove_const, :Template)
                end
            end
            # Validate no-sort parameters (if exist).
            unless parameters_no_sort.nil?
                if parameters_no_sort.is_a?(Array)
                    parameters_no_sort.each do |pns|
                        @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Non-existent #{Blufin::Terminal::format_highlight('PARAMETERS_NO_SORT')} parameter: #{Blufin::Terminal::format_invalid(pns)}" unless parameters.keys.include?(pns)
                    end
                else
                    @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 Expected constant #{Blufin::Terminal::format_highlight('PARAMETERS_NO_SORT')} to be Array, instead got: #{Blufin::Terminal::format_invalid(parameters_no_sort.class)}"
                end
            end
            # Validate template matchers.
            unless file_cloudformation.nil?
                results = App::Replacer::scan_file(file_cloudformation)
                # Handle errors first.
                validate_matchers(file_cloudformation, results, template_name, parameters)
            end
            @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 The #{Blufin::Terminal::format_highlight('template.yml')}\x1B[38;5;240m is missing, empty or invalid." if file_cloudformation.nil?
            if category == NESTED
                @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 #{Blufin::Terminal::format_highlight('template.rb')}\x1B[38;5;240m for nested stacks will be ignored, please remove." unless file_ruby.nil?
            else
                @warnings << "\x1B[38;5;196m#{template_name}\x1B[38;5;240m \xe2\x80\x94 The #{Blufin::Terminal::format_highlight('template.rb')}\x1B[38;5;240m is missing, empty or invalid." if file_ruby.nil?
                @templates[category] = {} unless @templates.has_key?(category)
                if @warnings.length > warnings_count
                    @templates[category][template] = {
                        :name   => template,
                        :broken => 'Broken'
                    }
                else
                    @templates[category][template]            = {
                        :name                   => template,
                        :path                   => template_path,
                        :broken                 => false,
                        :file_cloudformation    => file_cloudformation,
                        :file_ruby              => file_ruby,
                        :method_before_create   => method_before_create,
                        :method_after_create    => method_after_create,
                        :method_before_teardown => method_before_teardown,
                        :method_after_teardown  => method_after_teardown,
                        :parameters             => parameters,
                        :parameters_no_sort     => parameters_no_sort,
                        :intro                  => intro,
                        :description            => description,
                        :stack_name             => stack_name,
                        :projects               => projects,
                        :environments           => environments,
                        :regions                => regions,
                        :timeout                => timeout,
                        :single_serve           => single_serve
                    }
                    @templates[category][template][:stack_id] = stack_id unless stack_id.nil?
                end
            end
        end
    end

    system('clear')

    if @warnings.any?
        Blufin::Terminal::warning('Some template(s) had issues:', @warnings)
        # During test runs, bomb-out if there are warnings (otherwise continue).
        exit if @opts[:test]
    end

end