Class: Morpheus::Cli::BlueprintsCommand

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, OptionSourceHelper, ProvisioningHelper
Defined in:
lib/morpheus/cli/commands/blueprints_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from OptionSourceHelper

#find_available_user_option, #find_cloud_option, #find_group_option, #find_tenant_option, #get_available_user_options, #get_cloud_options, #get_group_options, #get_tenant_options, included, #load_option_source_data, #options_interface, #parse_cloud_id_list, #parse_group_id_list, #parse_option_source_id_list, #parse_project_id_list, #parse_tenant_id_list, #parse_user_id_list

Methods included from AccountsHelper

#account_column_definitions, #account_users_interface, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface

Methods included from ProvisioningHelper

#accounts_interface, #add_perms_options, #api_client, #apps_interface, #cloud_datastores_interface, #clouds_interface, #datastores_interface, #find_app_by_id, #find_app_by_name, #find_app_by_name_or_id, #find_cloud_by_id_for_provisioning, #find_cloud_by_name_for_provisioning, #find_cloud_by_name_or_id_for_provisioning, #find_cloud_resource_pool_by_name_or_id, #find_group_by_id_for_provisioning, #find_group_by_name_for_provisioning, #find_group_by_name_or_id_for_provisioning, #find_host_by_id, #find_host_by_name, #find_host_by_name_or_id, #find_instance_by_id, #find_instance_by_name, #find_instance_by_name_or_id, #find_instance_type_by_code, #find_instance_type_by_id, #find_instance_type_by_name, #find_instance_type_by_name_or_id, #find_instance_type_layout_by_id, #find_server_by_id, #find_server_by_name, #find_server_by_name_or_id, #find_workflow_by_id, #find_workflow_by_name, #find_workflow_by_name_or_id, #format_app_status, #format_blueprint_type, #format_container_connection_string, #format_container_status, #format_instance_connection_string, #format_instance_container_display_name, #format_instance_status, #format_metadata, #format_snapshot_status, #get_available_accounts, #get_available_clouds, #get_available_environments, #get_available_groups, #get_available_plans, #get_provision_type_for_zone_type, #get_static_environments, included, #instance_type_layouts_interface, #instance_types_interface, #instances_interface, #load_balance_protocols_dropdown, #options_interface, #parse_blueprint_type, #parse_host_id_list, #parse_instance_id_list, #parse_metadata, #parse_resource_id_list, #parse_server_id_list, #print_permissions, #prompt_evars, #prompt_exposed_ports, #prompt_instance_load_balancer, #prompt_metadata, #prompt_network_interfaces, #prompt_new_instance, #prompt_permissions, #prompt_permissions_v2, #prompt_resize_volumes, #prompt_security_groups, #prompt_service_plan_options, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeBlueprintsCommand

alias_subcommand :details, :get set_default_subcommand :list



26
27
28
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 26

def initialize() 
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#_get(arg, options) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 153

def _get(arg, options)
  connect(options)
  begin
    if options[:dry_run]
      @blueprints_interface.setopts(options)
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @blueprints_interface.dry.get(arg.to_i)
      else
        print_dry_run @blueprints_interface.dry.list({name:arg})
      end
      return
    end
    @blueprints_interface.setopts(options)
    blueprint = find_blueprint_by_name_or_id(arg)
    if blueprint.nil?
      return 1, "blueprint not found"
    end
    json_response = {'blueprint' => blueprint}  # skip redundant request
    #json_response = @blueprints_interface.get(blueprint['id'])
    blueprint = json_response['blueprint']

    # export just the config as json or yaml (default)
    if options[:show_config]
      unless options[:json] || options[:yaml] || options[:csv]
        options[:yaml] = true
      end
      return render_with_format(blueprint['config'], options)
    end
    render_response(json_response, options, 'blueprint') do
      print_h1 "Blueprint Details"
      print_blueprint_details(blueprint)
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 192

def add(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_option_type_options(opts, options, add_blueprint_option_types(false))
    opts.on('-t', '--type TYPE', String, "Blueprint Type. Default is morpheus.") do |val|
      options[:blueprint_type] = parse_blueprint_type(val.to_s)
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    build_standard_add_options(opts, options)
    opts.footer = "Create a new blueprint.\n" + 
                  "[name] is required. This is the name of the new blueprint."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:0, max:1)
  if args[0]
    options[:options]['name'] = args[0]
  end
  connect(options)
  begin
    payload = {}
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(passed_options) unless passed_options.empty?
    else
      # prompt for payload
      payload = {}
      payload.deep_merge!(passed_options) unless passed_options.empty?
      if options[:blueprint_type]
        options[:options]['type'] = options[:blueprint_type]
      else
        # options[:options]['type'] = 'morpheus'
      end
      params = Morpheus::Cli::OptionTypes.prompt(add_blueprint_option_types, options[:options], @api_client, options[:params])
      params.deep_compact!
      # expects no namespace, just the config
      payload.deep_merge!(params)
    end
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.create(payload)
      return
    end

    json_response = @blueprints_interface.create(payload)
    blueprint = json_response['blueprint']
    render_response(json_response, options, 'blueprint') do
      print_green_success "Added blueprint #{blueprint['name']}"
      if !options[:no_prompt]
        if options[:payload].nil? && ::Morpheus::Cli::OptionTypes::confirm("Would you like to add a tier now?", options.merge({default: false}))
          add_tier([blueprint['id']])
          while ::Morpheus::Cli::OptionTypes::confirm("Add another tier?", options.merge({default: false})) do
            add_tier([blueprint['id']])
          end
        else
          # print details
          return _get(blueprint["id"], options)
        end
      end
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_instance(args) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 601

def add_instance(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier] [instance-type]")
    # opts.on( '-g', '--group GROUP', "Group" ) do |val|
    #   options[:group] = val
    # end
    # opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
    #   options[:cloud] = val
    # end
    opts.on('--name VALUE', String, "Instance Name") do |val|
      options[:instance_name] = val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Update a blueprint, adding an instance." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint." + "\n" +
                  "[tier] is required and will be prompted for. This is the name of the tier." + "\n" +
                  "[instance-type] is required and will be prompted for. This is the type of instance."
  end
  optparse.parse!(args)

  if args.count < 1 || args.count > 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} add-instance expects 2-3 arguments and received #{args.count}: #{args}\n#{optparse}"
    return 1
  end

  connect(options)

  begin
    blueprint_name = args[0]
    tier_name = args[1]
    instance_type_code = args[2]
    # we also need consider when there is multiple instances of the same type in
    # a template/tier.. so maybe split instance_type_code as [type-code]:[index].. or...errr

    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    if !tier_name
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tierName', 'fieldLabel' => 'Tier Name', 'type' => 'text', 'required' => true, 'description' => 'Enter the name of the tier'}], options[:options])
      tier_name = v_prompt['tierName']
    end

    if !instance_type_code
      instance_type_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'fieldLabel' => 'Type', 'optionSource' => 'instanceTypes', 'required' => true, 'description' => 'Select Instance Type.'}],options[:options],api_client,{})
      instance_type_code = instance_type_prompt['type']
    end
    instance_type = find_instance_type_by_code(instance_type_code)
    return 1 if instance_type.nil?
    
    tier_config = nil
    instance_config = nil

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]
    tiers ||= {}
    # tier identified by name, case sensitive...
    if !tiers[tier_name]
      tiers[tier_name] = {}
    end
    tier_config = tiers[tier_name]
    
    instance_config = {'instance' => {'type' => instance_type['code']} }
    tier_config['instances'] ||= []
    tier_config['instances'].push(instance_config)

    # just prompts for Instance Name (optional)
    instance_name = nil
    if options[:instance_name]
      instance_name = options[:instance_name]
    else
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Instance Name', 'type' => 'text', 'defaultValue' => instance_config['instance']['name']}])
      instance_name = v_prompt['name'] || ''
    end
    
    if instance_name
      if instance_name.to_s == 'null'
        instance_config['instance'].delete('name')
        # instance_config['instance']['name'] = ''
      else
        instance_config['instance']['name'] = instance_name
      end
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return 0
    end

    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print_green_success "Instance added to blueprint #{blueprint['name']}"
      # prompt for new instance
      if !options[:no_prompt]
        if ::Morpheus::Cli::OptionTypes::confirm("Would you like to add a config now?", options.merge({default: true}))
          # todo: this needs to work by index, because you can have multiple instances of the same type
          # instance_identifier = instance_config['instance']['name'] # instance_type['code']
          instance_identifier = tier_config['instances'].size - 1
          add_instance_config([blueprint['id'], tier_name, instance_identifier])
          while ::Morpheus::Cli::OptionTypes::confirm("Add another config?", options.merge({default: false})) do
            add_instance_config([blueprint['id'], tier_name, instance_identifier])
          end
        else
          # print details
          get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
        end
      end
    end
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end

end

#add_instance_config(args) ⇒ Object



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 726

def add_instance_config(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier] [instance]")
    opts.on( '-g', '--group GROUP', "Group" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
      options[:cloud] = val
    end
    opts.on( '-e', '--env ENVIRONMENT', "Environment" ) do |val|
      options[:environment] = val
    end
    opts.on('--name VALUE', String, "Instance Name") do |val|
      options[:instance_name] = val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Update a blueprint, adding an instance config." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint." + "\n" +
                  "[tier] is required. This is the name of the tier." + "\n" +
                  "[instance] is required. This is the type of instance."
  end
  optparse.parse!(args)

  if args.count < 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "Wrong number of arguments"
    puts_error optparse
    return 1
  end

  connect(options)

  begin

    blueprint_name = args[0]
    tier_name = args[1]
    instance_identifier = args[2]

    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    # instance_type = find_instance_type_by_code(instance_type_code)
    # return 1 if instance_type.nil?
    
    tier_config = nil
    instance_config = nil

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]
    tiers ||= {}
    # tier identified by name, case sensitive...
    if !tiers[tier_name]
      tiers[tier_name] = {}
    end
    tier_config = tiers[tier_name]
    tier_config['instances'] ||= []
    matching_instance_configs = []
    if tier_config['instances']
      if instance_identifier.to_s =~ /\A\d{1,}\Z/
        matching_instance_configs = [tier_config['instances'][instance_identifier.to_i]].compact
      else
        tier_config['instances'] ||= []
        matching_instance_configs = []
        matching_instance_configs = (tier_config['instances'] || []).select {|instance_config| instance_config['instance'] && instance_config['instance']['name'] == instance_identifier }
        if matching_instance_configs.empty?
          matching_instance_configs = (tier_config['instances'] || []).select {|instance_config| instance_config['instance'] && instance_config['instance']['type'].to_s.downcase == instance_identifier.to_s.downcase }
        end
      end
    end

    if matching_instance_configs.size == 0
      print_red_alert "Instance not found by tier: #{tier_name}, type: #{instance_identifier}"
      return 1
    elsif matching_instance_configs.size > 1
      #print_error Morpheus::Terminal.angry_prompt
      print_red_alert  "More than one instance found by tier: #{tier_name}, type: #{instance_identifier}"
      puts_error "Try passing the name or index to identify the instance you wish to add a config to."
      puts_error optparse
      return 1
    end

    instance_config = matching_instance_configs[0]

    # group prompt

    # use active group by default
    #options[:group] ||= @active_group_id      

    # available_groups = get_available_groups()
    # group_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'fieldLabel' => 'Group', 'type' => 'select', 'selectOptions' => get_available_groups(), 'required' => true, 'defaultValue' => @active_group_id}],options[:options],@api_client,{})
    
    # group_id = group_prompt['group']
    # the_group = find_group_by_name_or_id_for_provisioning(group_id)

    # # cloud prompt
    # cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'optionSource' => 'clouds', 'required' => true, 'description' => 'Select Cloud.'}],options[:options],@api_client,{groupId: group_id})
    # cloud_id = cloud_prompt['cloud']

    # look for existing config for group + cloud

    options[:name_required] = false
    options[:instance_type_code] = instance_config['instance']['type'] #instance_type["code"]
    options[:for_app] = true
    options[:skip_labels_prompt] = true
    #options[:options].deep_merge!(specific_config)
    # this provisioning helper method handles all (most) of the parsing and prompting
    instance_config_payload = prompt_new_instance(options)

    # strip all empty string and nil, would be problematic for update()
    instance_config_payload.deep_compact!
    
    # puts "INSTANCE CONFIG YAML:"
    # puts as_yaml(instance_config_payload)
    
    selected_environment = instance_config_payload.delete('instanceContext') || instance_config_payload.delete('environment')
    # groom provision instance payload for template purposes
    selected_cloud_id = instance_config_payload.delete('zoneId')
    selected_site = instance_config_payload['instance'].delete('site')
    selected_site_id = selected_site['id']

    selected_group = find_group_by_name_or_id_for_provisioning(selected_site_id)
    selected_cloud = find_cloud_by_name_or_id_for_provisioning(selected_group['id'], selected_cloud_id)

    # store config in environments => env => groups => groupname => clouds => cloudname => 
    current_config = instance_config
    if selected_environment.to_s != ''
      instance_config['environments'] ||= {}
      instance_config['environments'][selected_environment] ||= {}
      current_config = instance_config['environments'][selected_environment]
    end

    current_config['groups'] ||= {}
    current_config['groups'][selected_group['name']] ||= {}
    current_config['groups'][selected_group['name']]['clouds'] ||= {}
    current_config['groups'][selected_group['name']]['clouds'][selected_cloud['name']] = instance_config_payload

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return 0
    end

    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      print_green_success "Instance added to blueprint #{blueprint['name']}"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end

end

#add_tier(args) ⇒ Object



1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1198

def add_tier(args)
  options = {}
  boot_order = nil
  linked_tiers = nil
  tier_index = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier]")
    opts.on('--name VALUE', String, "Tier Name") do |val|
      options[:name] = val
    end
    opts.on('--bootOrder NUMBER', String, "Boot Order" ) do |val|
      boot_order = val
    end
    opts.on('--linkedTiers x,y,z', Array, "Connected Tiers.") do |val|
      linked_tiers = val
    end
    opts.on('--tierIndex NUMBER', Array, "Tier Index. Used for Display Order") do |val|
      tier_index = val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} add-tier requires argument: [blueprint]\n#{optparse}"
    # puts optparse
    return 1
  end
  blueprint_name = args[0]
  tier_name = args[1]

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?
    
    blueprint["config"] ||= {}
    blueprint["config"]["tiers"] ||= {}
    tiers = blueprint["config"]["tiers"]

    # prompt new tier
    # Name
    # {'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1, 'description' => 'A unique name for the blueprint.'},
    #   {'fieldName' => 'bootOrder', 'fieldLabel' => 'Boot Order', 'type' => 'text', 'required' => false, 'displayOrder' => 2, 'description' => 'Boot Order'}
    if !tier_name
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Tier Name', 'type' => 'text', 'required' => true, 'description' => 'Enter the name of the tier'}], options[:options])
      tier_name = v_prompt['name']
    end
    # case insensitive match
    existing_tier_names = tiers.keys
    matching_tier_name = existing_tier_names.find {|k| k.downcase == tier_name.downcase }
    if matching_tier_name
      # print_red_alert "Tier #{tier_name} already exists"
      # return 1
      print cyan,"Tier #{tier_name} already exists.",reset,"\n"
      return 0
    end
    # idempotent
    if !tiers[tier_name]
      tiers[tier_name] = {'instances' => []}
    end
    tier = tiers[tier_name]
    
    # Boot Order
    if !boot_order
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'bootOrder', 'fieldLabel' => 'Boot Order', 'type' => 'text', 'required' => false, 'description' => 'Sequence order for starting app instances by tier. 0-N', 'defaultValue' => tier['bootOrder']}], options[:options])
      boot_order = v_prompt['bootOrder']
    end
    if boot_order.to_s == 'null'
      tier.delete('bootOrder')
    elsif boot_order.to_s != ''
      tier['bootOrder'] = boot_order.to_i
    end

    # Connected Tiers
    if !linked_tiers
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'linkedTiers', 'fieldLabel' => 'Connected Tiers', 'type' => 'text', 'required' => false, 'description' => 'Names of connected tiers, comma separated', 'defaultValue' => (linked_tiers ? linked_tiers.join(',') : nil)}], options[:options])
      linked_tiers = v_prompt['linkedTiers'].to_s.split(',').collect {|it| it.strip }.select {|it| it != ''}
    end
    if linked_tiers && !linked_tiers.empty?
      linked_tiers.each do |other_tier_name|
        link_result = link_tiers(tiers, [tier_name, other_tier_name])
        # could just re-prompt unless options[:no_prompt]
        return 1 if !link_result
      end
    end

    # Tier Index
    if !tier_index
      #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tierIndex', 'fieldLabel' => 'Tier Index', 'type' => 'number', 'required' => false, 'description' => 'Sequence order for displaying app instances by tier. 0-N', 'defaultValue' => tier['tierIndex']}], options[:options])
      #tier_index = v_prompt['tierIndex']
      tier_index = (tiers.size - 1)
    end

    if tier_index.to_s == 'null'
      tier.delete('tierIndex')
    elsif tier_index
      tier['tierIndex'] = tier_index.to_i
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = blueprint["config"]
    # payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print_green_success "Added tier #{tier_name}"
      # prompt for new instance
      if !options[:no_prompt]
        if ::Morpheus::Cli::OptionTypes::confirm("Would you like to add an instance now?", options.merge({default: true}))
          add_instance([blueprint['id'], tier_name])
          while ::Morpheus::Cli::OptionTypes::confirm("Add another instance now?", options.merge({default: false})) do
            add_instance([blueprint['id'], tier_name])
          end
          # if !add_instance_result
          # end
        end
      end
      # print details
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#available_tiers(args) ⇒ Object



1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1729

def available_tiers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  params = {}

  begin
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.list_tiers(params)
      return
    end
    json_response = @blueprints_interface.list_tiers(params)
    tiers = json_response["tiers"] # just a list of names
    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      print_h1 "Available Tiers"
      if tiers.empty?
        print cyan,"No tiers found.",reset,"\n"
      else
        print cyan
        tiers.each do |tier_name|
          puts tier_name
        end
      end
      print reset,"\n"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end

end

#connect(opts) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 30

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @blueprints_interface = @api_client.blueprints
  @groups_interface = @api_client.groups
  @instances_interface = @api_client.instances
  @instance_types_interface = @api_client.instance_types
  @options_interface = @api_client.options
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
  @clouds_interface = @api_client.clouds
  @account_users_interface = @api_client.
  @library_layouts_interface = @api_client.library_layouts
end

#connect_tiers(args) ⇒ Object



1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1548

def connect_tiers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [Tier1] [Tier2]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} connect-tiers expects 3 arguments and received #{args.count}: #{args}\n#{optparse}"
    # puts optparse
    return 1
  end
  blueprint_name = args[0]
  tier1_name = args[1]
  tier2_name = args[2]

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]

    if !tiers || tiers.keys.size == 0
      raise_command_error "Blueprint #{blueprint['name']} has no tiers."
    end

    tier1 = tiers[tier1_name]
    tier2 = tiers[tier2_name]
    # uhh support N args

    if tier1.nil?
      print_red_alert "Tier not found by name #{tier1_name}!"
      return 1
    end

    if tier2.nil?
      print_red_alert "Tier not found by name #{tier2_name}!"
      return 1
    end

    tier1["linkedTiers"] = tier1["linkedTiers"] || []
    tier2["linkedTiers"] = tier2["linkedTiers"] || []

    found_edge = tier1["linkedTiers"].include?(tier2_name) || tier2["linkedTiers"].include?(tier1_name)

    if found_edge
      puts cyan,"Tiers #{tier1_name} and #{tier2_name} are already connected.",reset
      return 0
    end

    # ok to be connect the tiers
    # note: the ui doesn't hook up both sides eh?

    if !tier1["linkedTiers"].include?(tier2_name)
      tier1["linkedTiers"].push(tier2_name)
    end

    if !tier2["linkedTiers"].include?(tier1_name)
      tier2["linkedTiers"].push(tier1_name)
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = blueprint["config"]
    # payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)


    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Connected 2 tiers for blueprint #{blueprint['name']}"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#disconnect_tiers(args) ⇒ Object



1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1640

def disconnect_tiers(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [Tier1] [Tier2]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} disconnect-tiers expects 3 arguments and received #{args.count}: #{args}\n#{optparse}"
    # puts optparse
    return 1
  end
  blueprint_name = args[0]
  tier1_name = args[1]
  tier2_name = args[2]

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]

    if !tiers || tiers.keys.size == 0
      # print_red_alert "Blueprint #{blueprint['name']} has no tiers."
      # raise_command_error "Blueprint #{blueprint['name']} has no tiers."
      print_error Morpheus::Terminal.angry_prompt
      puts_error  "Blueprint #{blueprint['name']} has no tiers."
      return 1
    end

    tier1 = tiers[tier1_name]
    tier2 = tiers[tier2_name]
    # uhh support N args

    if tier1.nil?
      print_red_alert "Tier not found by name #{tier1_name}!"
      return 1
    end

    if tier2.nil?
      print_red_alert "Tier not found by name #{tier2_name}!"
      return 1
    end

    tier1["linkedTiers"] = tier1["linkedTiers"] || []
    tier2["linkedTiers"] = tier2["linkedTiers"] || []

    found_edge = tier1["linkedTiers"].include?(tier2_name) || tier2["linkedTiers"].include?(tier1_name)

    if found_edge
      puts cyan,"Tiers #{tier1_name} and #{tier2_name} are not connected.",reset
      return 0
    end

    # remove links
    tier1["linkedTiers"] = tier1["linkedTiers"].reject {|it| it == tier2_name }
    tier2["linkedTiers"] = tier2["linkedTiers"].reject {|it| it == tier1_name }

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = blueprint["config"]
    # payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)


    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Connected 2 tiers for blueprint #{blueprint['name']}"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#duplicate(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 509

def duplicate(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [new name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Duplicate a blueprint." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint." + "\n" +
                  "[new name] is required. This is the name for the clone."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    exit 1
  end

  payload = {"blueprint" => {}}
  if args[1]
    payload["blueprint"]["name"] = args[1]
  end

  connect(options)
  begin
    blueprint = find_blueprint_by_name_or_id(args[0])
    exit 1 if blueprint.nil?
    # unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to duplicate the blueprint #{blueprint['name']}?")
    #   exit
    # end
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.duplicate(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.duplicate(blueprint['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      new_blueprint = json_response["blueprint"] || {}
      print_green_success "Created duplicate blueprint '#{new_blueprint['name']}'"
      #get([new_blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 131

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint]")
    opts.on( '-c', '--config', "Display raw config only. Default is YAML. Combine with -j for JSON instead." ) do
      options[:show_config] = true
    end
    build_standard_get_options(opts, options)
    opts.footer = "Get details about a blueprint.\n" +
                  "[blueprint] is required. This is the name or id of a blueprint. Supports 1-N [instance] arguments."
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args.join(', ')}\n#{optparse}"
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



43
44
45
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 43

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 47

def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('-t', '--type CODE', "Blueprint Type") do |val|
      params['type'] ||= []
      params['type'] << val
    end
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      params['ownerId'] ||= []
      params['ownerId'] << val
    end
    opts.on( '--created-by USER', "Alias for --owner" ) do |val|
      params['ownerId'] ||= []
      params['ownerId'] << val
    end
    opts.add_hidden_option('--created-by')
    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end
    build_standard_list_options(opts, options)
    opts.footer = "List blueprints."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  begin
    if params['ownerId']
      params['ownerId'] = params['ownerId'].collect do |owner_id|
        # user = find_user_by_username_or_id(nil, owner_id)
        user = find_available_user_option(owner_id)
        return 1 if user.nil?
        user['id']
      end
    end
    params.merge!(parse_list_options(options))
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.list(params)
      return
    end

    json_response = @blueprints_interface.list(params)
    blueprints = json_response['blueprints']

    if options[:json]
      puts as_json(json_response, options, "blueprints")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['blueprints'], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "blueprints")
      return 0
    end

    
    title = "Morpheus Blueprints"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    if blueprints.empty?
      print cyan,"No blueprints found.",reset,"\n"
    else
      print_blueprints_table(blueprints, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_types(args) ⇒ Object



1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1769

def list_types(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List blueprint types."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    params.merge!(parse_list_options(options))
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.list_types(params)
      return
    end

    json_response = @blueprints_interface.list_types(params)
    blueprint_types = json_response['types']

    if options[:json]
      puts as_json(json_response, options, "types")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['types'], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "types")
      return 0
    end

    
    title = "Morpheus Blueprint Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if blueprint_types.empty?
      print cyan,"No blueprint types found.",reset,"\n"
    else
      rows = blueprint_types.collect do |blueprint_type|
        {
          code: blueprint_type['code'],
          name: blueprint_type['name']
        }
      end
      columns = [:code, :name]
      print cyan
      print as_pretty_table(rows, columns, options)
      print reset
      # print_results_pagination(json_response)
    end
    print reset,"\n"
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 559

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint]")
    build_standard_remove_options(opts, options)
    opts.footer = "Delete a blueprint." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    exit 1
  end

  connect(options)
  begin
    blueprint = find_blueprint_by_name_or_id(args[0])
    exit 1 if blueprint.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the blueprint #{blueprint['name']}?")
      exit
    end
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.destroy(blueprint['id'])
      return
    end
    json_response = @blueprints_interface.destroy(blueprint['id'])

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Removed blueprint #{blueprint['name']}"
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_instance(args) ⇒ Object



1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1081

def remove_instance(args)
  #instance_index = nil
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier] [instance]")
    # opts.on('--index NUMBER', Number, "Identify Instance by index within tier, starting with 0." ) do |val|
    #   instance_index = val.to_i
    # end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Update a blueprint, removing a specified instance." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint." + "\n" +
                  "[tier] is required. This is the name of the tier." + "\n" +
                  "[instance] is required. This is the instance identifier, which may be the type, the name, or the index starting with 0."
  end
  
  optparse.parse!(args)
  
  if args.count != 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "Wrong number of arguments"
    puts_error optparse
    return 1
  end

  connect(options)

  begin

    blueprint_name = args[0]
    tier_name = args[1]
    instance_identifier = args[2]

    # instance_type_code = args[2]
    # we also need consider when there is multiple instances of the same type in
    # a template/tier.. so maybe split instance_type_code as [type-code]:[index].. or...errr

    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    # instance_type = find_instance_type_by_code(instance_type_code)
    # return 1 if instance_type.nil?
    
    tier_config = nil
    # instance_config = nil

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]
    tiers ||= {}
    # tier identified by name, case sensitive...
    if !tiers[tier_name]
      print_red_alert "Tier not found by name #{tier_name}"
      return 1
    end
    tier_config = tiers[tier_name]
    
    if tier_config['instances'].nil? || tier_config['instances'].empty?
      print_red_alert "Tier #{tier_name} is empty!"
      return 1
    end

    # find instance
    matching_indices = []
    if tier_config['instances']
      if instance_identifier.to_s =~ /\A\d{1,}\Z/
        matching_indices = [instance_identifier.to_i].compact
      else
        tier_config['instances'].each_with_index do |instance_config, index|
          if instance_config['instance'] && instance_config['instance']['type'].to_s.downcase == instance_identifier.to_s.downcase
            matching_indices << index
          elsif instance_config['instance'] && instance_config['instance']['name'] == instance_identifier
            matching_indices << index
          end
        end
      end
    end
    if matching_indices.size == 0
      print_red_alert "Instance not found by tier: #{tier_name}, instance: #{instance_identifier}"
      return 1
    elsif matching_indices.size > 1
      #print_error Morpheus::Terminal.angry_prompt
      print_red_alert "More than one instance matched tier: #{tier_name}, instance: #{instance_identifier}"
      puts_error "Try passing the name or index to identify the instance you wish to remove."
      puts_error optparse
      return 1
    end

    # remove it
    tier_config['instances'].delete_at(matching_indices[0])

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete this instance #{instance_identifier} instance from tier: #{tier_name}?")
      return 9
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      print_green_success "Removed instance from blueprint."
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_instance_config(args) ⇒ Object



889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 889

def remove_instance_config(args)
  #instance_index = nil
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier] [instance] -g GROUP -c CLOUD")
    opts.on( '-g', '--group GROUP', "Group" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
      options[:cloud] = val
    end
    opts.on( '-e', '--env ENV', "Environment" ) do |val|
      options[:environment] = val
    end
    # opts.on( nil, '--index NUMBER', "The index of the instance to remove, starting with 0." ) do |val|
    #   instance_index = val.to_i
    # end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Update a blueprint, removing a specified instance config." + "\n" +
                  "[blueprint] is required. This is the name or id of a blueprint." + "\n" +
                  "[tier] is required. This is the name of the tier." + "\n" +
                  "[instance] is required. This is the instance identifier, which may be the type, the name, or the index starting with 0." + "\n" +
                  "The config scope is specified with the -g GROUP, -c CLOUD and -e ENV. The -g and -c options are required."
  end
  optparse.parse!(args)
  
  if args.count != 3
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "Wrong number of arguments"
    puts_error optparse
    return 1
  end
  if !options[:group]
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "Missing required argument -g GROUP"
    puts_error optparse
    return 1
  end
  if !options[:cloud]
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "Missing required argument -c CLOUD"
    puts_error optparse
    return 1
  end
  connect(options)

  begin

    blueprint_name = args[0]
    tier_name = args[1]
    instance_identifier = args[2]

    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    # instance_type = find_instance_type_by_code(instance_type_code)
    # return 1 if instance_type.nil?
    
    tier_config = nil
    # instance_config = nil

    blueprint["config"] ||= {}
    tiers = blueprint["config"]["tiers"]
    tiers ||= {}
    # tier identified by name, case sensitive...
    if !tiers[tier_name]
      print_red_alert "Tier not found by name #{tier_name}"
      return 1
    end
    tier_config = tiers[tier_name]
    
    if !tier_config
      print_red_alert "Tier not found by name #{tier1_name}!"
      return 1
    elsif tier_config['instances'].nil? || tier_config['instances'].empty?
      print_red_alert "Tier #{tier_name} is empty!"
      return 1
    end

    matching_indices = []
    if tier_config['instances']
      if instance_identifier.to_s =~ /\A\d{1,}\Z/
        matching_indices = [instance_identifier.to_i].compact
      else
        tier_config['instances'].each_with_index do |instance_config, index|
          if instance_config['instance'] && instance_config['instance']['type'].to_s.downcase == instance_identifier.to_s.downcase
            matching_indices << index
          elsif instance_config['instance'] && instance_config['instance']['name'] == instance_identifier
            matching_indices << index
          end
        end
      end
    end


    if matching_indices.size == 0
      print_red_alert "Instance not found by tier: #{tier_name}, type: #{instance_identifier}"
      return 1
    elsif matching_indices.size > 1
      #print_error Morpheus::Terminal.angry_prompt
      print_red_alert  "More than one instance found by tier: #{tier_name}, type: #{instance_identifier}"
      puts_error "Try passing the name or index to identify the instance you wish to remove."
      puts_error optparse
      return 1
    end

    # ok, find the specified config
    instance_config = tier_config['instances'][matching_indices[0]]
    parent_config = nil
    current_config = instance_config
    delete_key = nil

    config_description = "type: #{instance_identifier}"
    config_description << " environment: #{options[:environment]}" if options[:environment]
    config_description << " group: #{options[:group]}" if options[:group]
    config_description << " cloud: #{options[:cloud]}" if options[:cloud]
    config_description = config_description.strip

    
    # find config in environments => env => groups => groupname => clouds => cloudname => 
    if options[:environment]
      if current_config && current_config['environments'] && current_config['environments'][options[:environment]]
        parent_config = current_config['environments']
        delete_key  = options[:environment]
        current_config = parent_config[delete_key]
      else
        print_red_alert "Instance config not found for scope #{config_description}"
        return 1
      end
    end
    if options[:group]
      if current_config && current_config['groups'] && current_config['groups'][options[:group]]
        parent_config = current_config['groups']
        delete_key  = options[:group]
        current_config = parent_config[delete_key]
      else
        print_red_alert "Instance config not found for scope #{config_description}"
        return 1
      end
    end
    if options[:cloud]
      if current_config && current_config['clouds'] && current_config['clouds'][options[:cloud]]
        parent_config = current_config['clouds']
        delete_key  = options[:cloud]
        current_config = parent_config[delete_key]
      else
        print_red_alert "Instance config not found for scope #{config_description}"
        return 1
      end
    end
    
    # remove it
    parent_config.delete(delete_key)
    
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete this instance config #{config_description} ?")
      return 9
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      print_green_success "Removed instance from blueprint."
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_tier(args) ⇒ Object



1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1481

def remove_tier(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} remove-tier expects 2 arguments and received #{args.count}: #{args}\n#{optparse}"
    return 1
  end
  blueprint_name = args[0]
  tier_name = args[1]

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?

    blueprint["config"] ||= {}
    blueprint["config"]["tiers"] ||= {}
    tiers = blueprint["config"]["tiers"]

    if !tiers[tier_name]
      # print_red_alert "Tier not found by name #{tier_name}"
      # return 1
      print cyan,"Tier #{tier_name} does not exist.",reset,"\n"
      return 0
    end

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the tier #{tier_name}?")
      exit
    end

    # remove it
    tiers.delete(tier_name)
    
    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = blueprint["config"]
    # payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end

    json_response = @blueprints_interface.update(blueprint['id'], payload)


    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Removed tier #{tier_name}"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 262

def update(args)
  payload, options = {}, {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [options]")
    build_option_type_options(opts, options, update_blueprint_option_types(false))
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      options[:owner] = val == 'null' ? nil : val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    build_standard_update_options(opts, options)
    opts.footer = "Update a blueprint.\n" + 
                  "[blueprint] is required. This is the name or id of a blueprint."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(', ')}\n#{optparse}"
  end
  connect(options)
  begin
    blueprint = find_blueprint_by_name_or_id(args[0])
    return 1 if blueprint.nil?
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!(parse_passed_options(options))
    else
      # no prompting, just merge passed options
      payload = blueprint["config"]
    end
    payload.deep_merge!(parse_passed_options(options))
    # Owner
    if options.key?(:owner)
      owner_id = options[:owner]
      if owner_id.to_s.empty?
        # allow clearing
        owner_id = nil
      elsif options[:owner]
        if owner_id.to_s =~ /\A\d{1,}\Z/
          # allow id without lookup
        else
          user = find_available_user_option(owner_id)
          return 1 if user.nil?
          owner_id = user['id']
        end
      end
      # payload['blueprint'] ||= {}
      # payload['blueprint']['ownerId'] = owner_id
      payload['ownerId'] = owner_id
    end
    if payload.empty?
      # this wont happen because its sending back the current config
      raise_command_error "Specify at least one option to update.\n#{optparse}"
    end
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end

    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      unless options[:quiet]
        blueprint = json_response['blueprint']
        print_green_success "Updated blueprint #{blueprint['name']}"
        get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
      end
    end

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_instance(args) ⇒ Object



1071
1072
1073
1074
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1071

def update_instance(args)
  print_red_alert "NOT YET SUPPORTED"
  return 5
end

#update_instance_config(args) ⇒ Object



1076
1077
1078
1079
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1076

def update_instance_config(args)
  print_red_alert "NOT YET SUPPORTED"
  return 5
end

#update_permissions(args) ⇒ Object



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
391
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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 342

def update_permissions(args)
  payload, options = {}, {}
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [options]")
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on( '--owner USER', "Owner Username or ID" ) do |val|
      options[:owner] = val == 'null' ? nil : val
    end
    build_option_type_options(opts, options, update_blueprint_option_types(false))
    build_standard_update_options(opts, options)
    opts.footer = "Update a blueprint permissions.\n" + 
                  "[blueprint] is required. This is the name or id of a blueprint."
  end
  optparse.parse!(args)

  if args.count != 1
    puts optparse
    return 1
  end

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(args[0])
    return 1 if blueprint.nil?
    if options[:payload]
      payload = options[:payload]
    end
    payload['blueprint'] ||= {}
    payload.deep_merge!(parse_passed_options(options))
    # Group Access
    if group_access_all != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['all'] = group_access_all
    end
    if group_access_list != nil
      payload['resourcePermissions'] ||= {}
      payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
        site = {"id" => site_id.to_i}
        if group_defaults_list && group_defaults_list.include?(site_id)
          site["default"] = true
        end
        site
      end
    end
    # Visibility
    if options['visibility'] != nil
      payload['blueprint']['visibility'] = options['visibility'].to_s.downcase
    end
    # Owner
    if options.key?(:owner)
      owner_id = options[:owner]
      if owner_id.to_s.empty?
        # allow clearing
        owner_id = nil
      elsif options[:owner]
        if owner_id.to_s =~ /\A\d{1,}\Z/
          # allow id without lookup
        else
          user = find_available_user_option(owner_id)
          return 1 if user.nil?
          owner_id = user['id']
        end
      end
      payload['blueprint']['ownerId'] = owner_id
    end
    if payload['blueprint'] && payload['blueprint'].empty?
      payload.delete('blueprint')
    end
    if payload.empty?
      raise_command_error "Specify at least one option to update.\n#{optparse}" if payload.empty?
    end
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update_permissions(blueprint['id'], payload)
      return
    end

    json_response = @blueprints_interface.update_permissions(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    else
      unless options[:quiet]
        blueprint = json_response['blueprint']
        print_green_success "Updated permissions for blueprint #{blueprint['name']}"
        get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_tier(args) ⇒ Object



1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 1336

def update_tier(args)
  options = {}
  new_tier_name = nil
  boot_order = nil
  linked_tiers = nil
  tier_index = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [tier]")
    opts.on('--name VALUE', String, "Tier Name") do |val|
      new_tier_name = val
    end
    opts.on('--bootOrder NUMBER', String, "Boot Order" ) do |val|
      boot_order = val
    end
    opts.on('--linkedTiers x,y,z', Array, "Connected Tiers") do |val|
      linked_tiers = val
    end
    opts.on('--tierIndex NUMBER', String, "Tier Index. Used for Display Order") do |val|
      tier_index = val.to_i
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count != 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} update-tier expects 2 arguments and received #{args.count}: #{args}\n#{optparse}"
    return 1
  end
  blueprint_name = args[0]
  tier_name = args[1]

  connect(options)

  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    return 1 if blueprint.nil?
    
    blueprint["config"] ||= {}
    blueprint["config"]["tiers"] ||= {}
    tiers = blueprint["config"]["tiers"]
    
    if !tiers[tier_name]
      print_red_alert "Tier not found by name #{tier_name}"
      return 1
    end
    tier = tiers[tier_name]

    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    
    if options[:no_prompt]
      if !(new_tier_name || boot_order || linked_tiers || tier_index || !passed_options.empty?)
        print_error Morpheus::Terminal.angry_prompt
        puts_error  "#{command_name} update-tier requires an option to update.\n#{optparse}"
        return 1
      end
    end

    tier.deep_merge!(passed_options) unless passed_options.empty?

    # prompt update tier
    # Name
    if !new_tier_name
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Tier Name', 'type' => 'text', 'required' => true, 'description' => 'Rename the tier', 'defaultValue' => tier_name}], options[:options])
      new_tier_name = v_prompt['name']
    end
    if new_tier_name && new_tier_name != tier_name
      if tiers[new_tier_name]
        print_red_alert "A tier named #{tier_name} already exists."
        return 1
      end
      tier = tiers.delete(tier_name)
      tiers[new_tier_name] = tier
      # Need to fix all the linkedTiers
      tiers.each do |k, v|
        if v['linkedTiers'] && v['linkedTiers'].include?(tier_name)
          v['linkedTiers'] = v['linkedTiers'].map {|it| it == tier_name ? new_tier_name : it }
        end
      end
      tier_name = new_tier_name
    end

    # Boot Order
    if !boot_order
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'bootOrder', 'fieldLabel' => 'Boot Order', 'type' => 'text', 'required' => false, 'description' => 'Sequence order for starting app instances by tier. 0-N', 'defaultValue' => tier['bootOrder']}], options[:options])
      boot_order = v_prompt['bootOrder']
    end
    if boot_order.to_s == 'null'
      tier.delete('bootOrder')
    elsif boot_order.to_s != ''
      tier['bootOrder'] = boot_order.to_i
    end

    # Connected Tiers
    if !linked_tiers
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'linkedTiers', 'fieldLabel' => 'Connected Tiers', 'type' => 'text', 'required' => false, 'description' => 'Names of connected tiers, comma separated', 'defaultValue' => (tier['linkedTiers'] ? tier['linkedTiers'].join(',') : nil)}], options[:options])
      linked_tiers = v_prompt['linkedTiers'].to_s.split(',').collect {|it| it.strip }.select {|it| it != ''}
    end
    current_linked_tiers = tier['linkedTiers'] || []
    if linked_tiers && linked_tiers != current_linked_tiers
      remove_tiers = current_linked_tiers - linked_tiers
      remove_tiers.each do |other_tier_name|
        unlink_result = unlink_tiers(tiers, [tier_name, other_tier_name])
        # could just re-prompt unless options[:no_prompt]
        return 1 if !unlink_result
      end
      add_tiers = linked_tiers - current_linked_tiers
      add_tiers.each do |other_tier_name|
        link_result = link_tiers(tiers, [tier_name, other_tier_name])
        # could just re-prompt unless options[:no_prompt]
        return 1 if !link_result
      end
    end

    # Tier Index
    if tier_index.to_s == 'null'
      tier.delete('tierIndex')
    elsif tier_index
      tier['tierIndex'] = tier_index.to_i
    end

    # ok, make api request
    blueprint["config"]["tiers"] = tiers
    payload = blueprint["config"]
    # payload = {blueprint: blueprint}
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.update(blueprint['id'], payload)
      return
    end
    json_response = @blueprints_interface.update(blueprint['id'], payload)

    if options[:json]
      puts JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print_green_success "Updated tier #{tier_name}"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#upload_image(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/blueprints_command.rb', line 454

def upload_image(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[blueprint] [file]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
    opts.footer = "Upload an image file to be used as the icon for a blueprint.\n" + 
                  "[blueprint] is required. This is the name or id of a blueprint.\n" +
                  "[file] is required. This is the local path of a file to upload [png|jpg|svg]."
  end
  optparse.parse!(args)
  if args.count != 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} upload-image expects 2 arguments and received #{args.count}: #{args}\n#{optparse}"
    return 1
  end
  blueprint_name = args[0]
  filename = File.expand_path(args[1].to_s)
  image_file = nil
  if filename && File.file?(filename)
    # maybe validate it's an image file? [.png|jpg|svg]
    image_file = File.new(filename, 'rb')
  else
    print_red_alert "File not found: #{filename}"
    # print_error Morpheus::Terminal.angry_prompt
    # puts_error  "bad argument [file] - File not found: #{filename}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    blueprint = find_blueprint_by_name_or_id(blueprint_name)
    exit 1 if blueprint.nil?
    @blueprints_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @blueprints_interface.dry.save_image(blueprint['id'], image_file)
      return 0
    end
    unless options[:quiet] || options[:json]
      print cyan, "Uploading file #{filename} ...", reset, "\n"
    end
    json_response = @blueprints_interface.save_image(blueprint['id'], image_file)
    if options[:json]
      print JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      blueprint = json_response['blueprint']
      new_image_url = blueprint['image']
      print cyan, "Updated blueprint #{blueprint['name']} image.\nNew image url is: #{new_image_url}", reset, "\n\n"
      get([blueprint['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end