Method: AppCommand::CloudFormationCreate#opts_routing

Defined in:
lib/routes/cloudformation_create.rb

#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