Class: Morpheus::Cli::ImageBuilderCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand, ProvisioningHelper
Defined in:
lib/morpheus/cli/image_builder_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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_resize_volumes, #prompt_security_groups, #prompt_volumes, #provision_types_interface, #reject_service_plan_option_types, #servers_interface

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_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, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #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

#initializeImageBuilderCommand

set_default_subcommand :list



27
28
29
# File 'lib/morpheus/cli/image_builder_command.rb', line 27

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

Instance Method Details

#add(args) ⇒ Object



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
391
392
# File 'lib/morpheus/cli/image_builder_command.rb', line 272

def add(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[options]")
    # build_option_type_options(opts, options, add_image_build_option_types(false))
    opts.on( '-t', '--type TYPE', "Image Build Type" ) do |val|
      options['type'] = val
    end
    opts.on('--name VALUE', String, "Name") do |val|
      options['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      options['description'] = val
    end
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options['group'] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options['cloud'] = val
    end
    # opts.on( '-e', '--env ENVIRONMENT', "Environment" ) do |val|
    #   options[:cloud] = val
    # end
    opts.on('--config JSON', String, "Instance Config JSON") do |val|
      options['config'] = JSON.parse(val.to_s)
    end
    opts.on('--config-yaml YAML', String, "Instance Config YAML") do |val|
      options['config'] = YAML.load(val.to_s)
    end
    opts.on('--config-file FILE', String, "Instance Config from a local JSON or YAML file") do |val|
      options['configFile'] = val.to_s
    end
    # opts.on('--configFile FILE', String, "Instance Config from a local file") do |val|
    #   options['configFile'] = val.to_s
    # end
    opts.on('--bootScript VALUE', String, "Boot Script ID") do |val|
      options['bootScript'] = val.to_s
    end
    opts.on('--bootCommand VALUE', String, "Boot Command. This can be used in place of a bootScript") do |val|
      options['bootCommand'] = val.to_s
    end
    opts.on('--preseedScript VALUE', String, "Preseed Script ID") do |val|
      options['preseedScript'] = val.to_s
    end
    opts.on('--scripts LIST', String, "Additional Scripts (comma separated names or ids)") do |val|
      # uh don't put commas or leading/trailing spaces in script names pl
      options['scripts'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    end
    opts.on('--sshUsername VALUE', String, "SSH Username") do |val|
      options['sshUsername'] = val.to_s
    end
    opts.on('--sshPassword VALUE', String, "SSH Password") do |val|
      options['sshPassword'] = val.to_s
    end
    opts.on('--storageProvider VALUE', String, "Storage Provider ID") do |val|
      options['storageProvider'] = val.to_s
    end
    opts.on('--isCloudInit [on|off]', String, "Cloud Init?") do |val|
      options['isCloudInit'] = (val.to_s == 'on' || val.to_s == 'true')
    end
    opts.on('--buildOutputName VALUE', String, "Build Output Name") do |val|
      options['buildOutputName'] = val.to_s
    end
    opts.on('--conversionFormats VALUE', String, "Conversion Formats ie. ovf, qcow2, vhd") do |val|
      options['conversionFormats'] = val.to_s
    end
    opts.on('--keepResults VALUE', String, "Keep only the most recent builds. Older executions will be deleted along with their associated Virtual Images. The value 0 disables this functionality.") do |val|
      options['keepResults'] = val.to_i
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
  end
  optparse.parse!(args)
  if args.count > 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 0-1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support options top of --payload
      options.merge!(options[:options]) if options[:options] # so -O var= works..
      option_params = options.reject {|k,v| k.is_a?(Symbol) }
      payload.deep_merge!({'imageBuild' => option_params}) unless option_params.empty?
    else
      options.merge!(options[:options]) if options[:options] # so -O var= works..

      # use the -g GROUP or active group by default
      # options['group'] ||=  @active_group_id
      
      # support first arg as name instead of --name
      if args[0] && !options['name']
        options['name'] = args[0]
      end

      image_build_payload = prompt_new_image_build(options)
      return 1 if !image_build_payload
      payload = {'imageBuild' => image_build_payload}
    end
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @image_builds_interface.dry.create(payload)
      return
    end
    json_response = @image_builds_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      new_image_build = json_response['imageBuild']
      print_green_success "Added image build #{new_image_build['name']}"
      get([new_image_build['id']])
      # list([])
    end

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

#boot_scripts(args) ⇒ Object



49
50
51
# File 'lib/morpheus/cli/image_builder_command.rb', line 49

def boot_scripts(args)
  Morpheus::Cli::BootScriptsCommand.new.handle(args)
end

#connect(opts) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/morpheus/cli/image_builder_command.rb', line 31

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @image_builder_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).image_builder
  @image_builds_interface = @image_builder_interface.image_builds
  @boot_scripts_interface = @image_builder_interface.boot_scripts
  @preseed_scripts_interface = @image_builder_interface.preseed_scripts
  @groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
  @clouds_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).clouds
  @instances_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instances
  @instance_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instance_types
  @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end

#delete_execution(args) ⇒ Object



652
653
654
655
# File 'lib/morpheus/cli/image_builder_command.rb', line 652

def delete_execution(args)
  puts "todo: implement me"
  return 0
end

#get(args) ⇒ Object



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
# File 'lib/morpheus/cli/image_builder_command.rb', line 134

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image-build]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [image-build]\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @image_builds_interface.dry.get(args[0].to_i)
      else
        print_dry_run @image_builds_interface.dry.list({name:args[0]})
      end
      return
    end
    image_build = find_image_build_by_name_or_id(args[0])
    return 1 if image_build.nil?
    # json_response = {'imageBuild' => image_build}  # skip redundant request
    json_response = @image_builds_interface.get(image_build['id'])
    image_build = json_response['imageBuild']
    if options[:json]
      print JSON.pretty_generate(json_response)
      return
    end
    print_h1 "Image Build Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      # "Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Name" => 'name',
      "Description" => 'description',
      "Group" => lambda {|it| it['site'] ? it['site']['name'] : '' },
      "Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
      "Plan" => lambda {|it| 
        if it['config'] && it['config']['plan']
          it['config']['plan']['code'] # name needed!
        else
          ""
        end
      },
      "Image" => lambda {|it| 
        if it['config'] && it['config']['template']
          it['config']['template']
        elsif it['config'] && it['config']['image']
          it['config']['image']
        else
          ""
        end
      },
      "Boot Script" => lambda {|it| 
        if it['bootScript']
          if it['bootScript'].kind_of?(Hash)
             it['bootScript']['fileName'] || it['bootScript']['name']  || it['bootScript']['id']
          else
            it['bootScript']
          end
        else
          ""
        end
      },
      "Preseed Script" => lambda {|it| 
        if it['preseedScript']
          if it['preseedScript'].kind_of?(Hash)
            it['preseedScript']['fileName'] || it['preseedScript']['name'] || it['preseedScript']['id']
          else
            it['preseedScript']
          end
        else
          ""
        end
      },
      # Additional Scripts
      "Scripts" => lambda {|it|
        if it['scripts']
          script_names = it['scripts'].collect do |script|
            if script.kind_of?(Hash)
              script['name']
            else
              script
            end
          end
          script_names.join(", ")
        else
          ""
        end
      },
      "SSH Username" => lambda {|it| it['sshUsername'] },
      "SSH Password" => lambda {|it| it['sshPassword'].to_s.empty? ? '' : '(hidden)' }, # api returns masked
      "Storage Provider" => lambda {|it| 
        if it['storageProvider']
          if it['storageProvider'].kind_of?(Hash)
            it['storageProvider']['name'] || it['storageProvider']['id']
          else
            it['storageProvider']
          end
        else
          ""
        end
      },
      "Build Output Name" => lambda {|it| it['buildOutputName'] },
      "Conversion Formats" => lambda {|it| it['conversionFormats'] },
      "Cloud Init?" => lambda {|it| it['isCloudInit'] ? 'Yes' : 'No' },
      "Keep Results" => lambda {|it| it['keepResults'].to_i == 0 ? 'All' : it['keepResults'] },
      "Last Run Date" => lambda {|it| 
        last_result = it['lastResult']
        last_result ? format_local_dt(last_result['startDate']) : ''
      },
      "Status" => lambda {|it| format_image_build_status(it) },
    }
    print_description_list(description_cols, image_build)

    #json_response = @image_builds_interface.list_executions(image_build['id'], params)
    image_build_executions = json_response['imageBuildExecutions'] # yep, show() returns the last 100 run
    image_build_executions = image_build_executions.first(10) # limit to just 10
    if image_build_executions && image_build_executions.size > 0
      print_h2 "Recent Executions"
      print_image_build_executions_table(image_build_executions, opts={})
      print_results_pagination({size:image_build_executions.size,total:image_build['executionCount'].to_i}, {:label => "execution", :n_label => "executions"})
    else
      puts "\nNo executions found.\n"
    end

    print reset,"\n"

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

#handle(args) ⇒ Object



45
46
47
# File 'lib/morpheus/cli/image_builder_command.rb', line 45

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
130
131
132
# File 'lib/morpheus/cli/image_builder_command.rb', line 57

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    params = {}
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @image_builds_interface.dry.list(params)
      return
    end

    json_response = @image_builds_interface.list(params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    image_builds = json_response['imageBuilds']
    title = "Morpheus Image Builds"
    subtitles = []
    # if group
    #   subtitles << "Group: #{group['name']}".strip
    # end
    # if cloud
    #   subtitles << "Cloud: #{cloud['name']}".strip
    # end
    if params[:phrase]
      subtitles << "Search: #{params[:phrase]}".strip
    end
    print_h1 title, subtitles
    if image_builds.empty?
      print cyan,"No image builds found.",reset,"\n"
    else
      rows = image_builds.collect {|image_build| 
          last_result = image_build['lastResult']
          status_str = format_image_build_status(image_build, cyan)
          result_str = format_image_build_execution_result(last_result, cyan)
          row = {
            id: image_build['id'],
            name: image_build['name'],
            # description: image_build['description'],
            type: image_build['type'] ? image_build['type']['name'] : 'N/A',
            group: image_build['site'] ? image_build['site']['name'] : '',
            cloud: image_build['zone'] ? image_build['zone']['name'] : '',
            executionCount: image_build['executionCount'] ? image_build['executionCount'].to_i : '',
            lastRunDate: last_result ? format_local_dt(last_result['startDate']) : '',
            status: status_str,
            result: result_str
          }
          row
        }
        columns = [:id, :name, :type, {:lastRunDate => {label: 'Last Run Date'.upcase}}, 
                    :status, {:result => {max_width: 60}}]
        # custom pretty table columns ...
        if options[:include_fields]
          columns = options[:include_fields]
        end
        print cyan
        print as_pretty_table(rows, columns, options)
        print reset
        print_results_pagination(json_response)
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_executions(args) ⇒ Object



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
# File 'lib/morpheus/cli/image_builder_command.rb', line 606

def list_executions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image-build]")
    build_common_options(opts, options, [:list, :json, :dry_run, :remote])
    opts.footer = "List executions for an image build."
    opts.footer = "Display a list of executions for an image build.\n"
                  "[image-build] is the name or id of an image build."
  end
  optparse.parse!(args)
  if args.count > 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)

  image_build = find_image_build_by_name_or_id(args[0])
  return 1 if image_build.nil?
  

  params = {}
  [:phrase, :offset, :max, :sort, :direction].each do |k|
    params[k] = options[k] unless options[k].nil?
  end
  @image_builds_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @image_builds_interface.dry.list_executions(image_build['id'], params)
    return 0
  end
  json_response = @image_builds_interface.list_executions(image_build['id'], params)
  if options[:json]
    puts JSON.pretty_generate(json_response)
    return 0
  end
  image_build = json_response['imageBuild']
  image_build_executions = json_response['imageBuildExecutions']
  print_h1 "Image Build Executions: [#{image_build['id']}] #{image_build['name']}"
  print cyan
  if image_build_executions && image_build_executions.size > 0
    print_image_build_executions_table(image_build_executions, opts={})
    print_results_pagination(json_response, {:label => "execution", :n_label => "executions"})
  end

  return 0
end

#preseed_scripts(args) ⇒ Object



53
54
55
# File 'lib/morpheus/cli/image_builder_command.rb', line 53

def preseed_scripts(args)
  Morpheus::Cli::PreseedScriptsCommand.new.handle(args)
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/image_builder_command.rb', line 513

def remove(args)
  options = {}
  query_params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image-build]")
    opts.on( '-K', '--keep-virtual-images', "Preserve associated virtual images" ) do
      query_params['keepVirtualImages'] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [image-build]\n#{optparse}"
    return 1
  end

  connect(options)
  begin
    image_build = find_image_build_by_name_or_id(args[0])
    return 1 if image_build.nil?

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the image build: #{image_build['name']}?")
      return 9, "aborted command"
    end
    if query_params['keepVirtualImages'].nil?
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'keepVirtualImages', 'type' => 'checkbox', 'fieldLabel' => 'Keep Virtual Images?', 'required' => false, 'defaultValue' => false, 'description' => 'Preserve associated virtual images. By default, they are deleted as well.'}],options,@api_client,{})
      query_params['keepVirtualImages'] = v_prompt['keepVirtualImages']
    end
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @image_builds_interface.dry.destroy(image_build['id'], query_params)
      return 0
    end
    json_response = @image_builds_interface.destroy(image_build['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Removed image build #{image_build['name']}"
      # list([])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#run(args) ⇒ Object



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
# File 'lib/morpheus/cli/image_builder_command.rb', line 563

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

  if args.count < 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "#{command_name} missing argument: [image-build]\n#{optparse}"
    return 1
  end

  connect(options)
  begin
    image_build = find_image_build_by_name_or_id(args[0])
    return 1 if image_build.nil?

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to run the image build: #{image_build['name']}?")
      return 9, "aborted command"
    end
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @image_builds_interface.dry.run(image_build['id'], query_params)
      return 0
    end
    json_response = @image_builds_interface.run(image_build['id'], query_params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "New run started for image build #{image_build['name']}"
      get([image_build['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#update(args) ⇒ Object



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
# File 'lib/morpheus/cli/image_builder_command.rb', line 394

def update(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[image-build] [options]")
    # build_option_type_options(opts, options, update_image_build_option_types(false))
    # cannot update type
    opts.on( '-t', '--type TYPE', "Image Build Type" ) do |val|
      options['type'] = val
    end
    opts.on('--name VALUE', String, "New Name") do |val|
      options['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      options['description'] = val
    end
    opts.on( '-g', '--group GROUP', "Group Name or ID" ) do |val|
      options['group'] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      options['cloud'] = val
    end
    # opts.on( '-e', '--env ENVIRONMENT', "Environment" ) do |val|
    #   options[:cloud] = val
    # end
    opts.on('--config JSON', String, "Instance Config JSON") do |val|
      options['config'] = JSON.parse(val.to_s)
    end
    opts.on('--config-yaml YAML', String, "Instance Config YAML") do |val|
      options['config'] = YAML.load(val.to_s)
    end
    opts.on('--config-file FILE', String, "Instance Config from a local JSON or YAML file") do |val|
      options['configFile'] = val.to_s
    end
    # opts.on('--configFile FILE', String, "Instance Config from a local file") do |val|
    #   options['configFile'] = val.to_s
    # end
    opts.on('--bootScript VALUE', String, "Boot Script ID") do |val|
      options['bootScript'] = val.to_s
    end
    opts.on('--bootCommand VALUE', String, "Boot Command. This can be used in place of a bootScript") do |val|
      options['bootCommand'] = val.to_s
    end
    opts.on('--preseedScript VALUE', String, "Preseed Script ID") do |val|
      options['preseedScript'] = val.to_s
    end
    opts.on('--scripts LIST', String, "Additional Scripts (comma separated names or ids)") do |val|
      # uh don't put commas or leading/trailing spaces in script names pl
      options['scripts'] = val.to_s.split(",").collect {|it| it.to_s.strip }.select {|it| it }.compact
    end
    opts.on('--sshUsername VALUE', String, "SSH Username") do |val|
      options['sshUsername'] = val.to_s
    end
    opts.on('--sshPassword VALUE', String, "SSH Password") do |val|
      options['sshPassword'] = val.to_s
    end
    opts.on('--storageProvider VALUE', String, "Storage Provider ID") do |val|
      options['storageProvider'] = val.to_s
    end
    opts.on('--isCloudInit [on|off]', String, "Cloud Init?") do |val|
      options['isCloudInit'] = (val.to_s == 'on' || val.to_s == 'true')
    end
    opts.on('--buildOutputName VALUE', String, "Build Output Name") do |val|
      options['buildOutputName'] = val.to_s
    end
    opts.on('--conversionFormats VALUE', String, "Conversion Formats ie. ovf, qcow2, vhd") do |val|
      options['conversionFormats'] = val.to_s
    end
    # opts.on('--keepResultsEnabled [on|off]', String, "Delete Old Results. Enables the Keep Results option") do |val|
    #   options['keepResultsEnabled'] = (val.to_s == 'on' || val.to_s == 'true')
    # end
    opts.on('--keepResults VALUE', String, "Keep only the most recent builds. Older executions will be deleted along with their associated Virtual Images. The value 0 disables this functionality.") do |val|
      options['keepResults'] = val.to_i
      # 0 disables it
      # options['deleteOldResults'] = (options['keepResults'] > 0)
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
  end
  optparse.parse!(args)
  if args.count != 1
    puts_error  "#{Morpheus::Terminal.angry_prompt}wrong number of arguments. Expected 1 and received #{args.count} #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    image_build = find_image_build_by_name_or_id(args[0])
    return 1 if !image_build
    payload = nil
    if options[:payload]
      payload = options[:payload]
      # support options top of --payload
      options.merge!(options[:options]) if options[:options] # so -O var= works..
      option_params = options.reject {|k,v| k.is_a?(Symbol) }
      payload.deep_merge!({'imageBuild' => option_params}) unless option_params.empty?
    else
      options.merge!(options[:options]) if options[:options] # so -O var= works..
      image_build_payload = prompt_edit_image_build(image_build, options)
      return 1 if !image_build_payload
      payload = {'imageBuild' => image_build_payload}
    end
    @image_builds_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @image_builds_interface.dry.update(image_build["id"], payload)
      return
    end
    json_response = @image_builds_interface.update(image_build["id"], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Updated image build #{image_build['name']}"
      get([image_build['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end