Class: Morpheus::Cli::Roles

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand, ProvisioningHelper
Defined in:
lib/morpheus/cli/roles.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_blueprint_type, #format_metadata, #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 AccountsHelper

#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, #get_access_color, #get_access_string, included, #print_accounts_table, #print_roles_table, #print_users_table, #roles_interface, #user_groups_interface, #users_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_name, #default_refresh_interval, #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, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #verify_args!, #visible_subcommands

Instance Method Details

#add(args) ⇒ Object



415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/morpheus/cli/roles.rb', line 415

def add(args)
  usage = "Usage: morpheus roles add [options]"
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_option_type_options(opts, options, add_role_option_types)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args}\n#{optparse}"
  end
  if args[0]
    options[:options]['authority'] = args[0]
  end
  connect(options)
  begin

    load_whoami()
     = (options)
     =  ? ['id'] : nil

    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'role' => passed_options}) unless passed_options.empty?
    else
      # merge -O options into normally parsed options
      params.deep_merge!(passed_options)

      # argh, some options depend on others here...eg. multitenant is only available when roleType == 'user'
      #prompt_option_types = update_role_option_types()

      role_payload = params
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'authority', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'displayOrder' => 1}], options[:options])
      role_payload['authority'] = v_prompt['authority']
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'displayOrder' => 2}], options[:options])
      role_payload['description'] = v_prompt['description']

      if @is_master_account
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'roleType', 'fieldLabel' => 'Type', 'type' => 'select', 'selectOptions' => role_type_options, 'defaultValue' => 'user', 'displayOrder' => 3}], options[:options])
        role_payload['roleType'] = v_prompt['roleType']
      else
        role_payload['roleType'] = 'user'
      end

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'baseRole', 'fieldLabel' => 'Copy From Role', 'type' => 'text', 'displayOrder' => 4}], options[:options])
      if v_prompt['baseRole'].to_s != ''
        base_role = find_role_by_name_or_id(, v_prompt['baseRole'])
        exit 1 if base_role.nil?
        role_payload['baseRoleId'] = base_role['id']
      end

      if @is_master_account
        if role_payload['roleType'] == 'user'
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'multitenant', 'fieldLabel' => 'Multitenant', 'type' => 'checkbox', 'defaultValue' => 'off', 'description' => 'A Multitenant role is automatically copied into all existing subaccounts as well as placed into a subaccount when created. Useful for providing a set of predefined roles a Customer can use', 'displayOrder' => 5}], options[:options])
          role_payload['multitenant'] = ['on','true'].include?(v_prompt['multitenant'].to_s)
          if role_payload['multitenant']
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'multitenantLocked', 'fieldLabel' => 'Multitenant Locked', 'type' => 'checkbox', 'defaultValue' => 'off', 'description' => 'Prevents subtenants from branching off this role/modifying it. '}], options[:options])
            role_payload['multitenantLocked'] = ['on','true'].include?(v_prompt['multitenantLocked'].to_s)
          end
        end
      end

      payload = {"role" => role_payload}
    end
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.create(, payload)
      return
    end
    json_response = @roles_interface.create(, payload)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end

    role = json_response['role']
    display_name = role['authority'] rescue ''
    if 
      print_green_success "Added role #{display_name} to account #{['name']}"
    else
      print_green_success "Added role #{display_name}"
    end

    get_args = [role['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
    if 
      get_args.push "--account-id", ['id'].to_s
    end

    details_options = [role_payload["authority"]]
    if 
      details_options.push "--account-id", ['id'].to_s
    end
    get(details_options)

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

#connect(opts) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/morpheus/cli/roles.rb', line 19

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @whoami_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).whoami
  @users_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).users
  @accounts_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).accounts
  @roles_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).roles
  @groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
  @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
  @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
  @blueprints_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).blueprints
  @active_group_id = Morpheus::Cli::Groups.active_groups[@appliance_name]
end

#get(args) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/morpheus/cli/roles.rb', line 89

def get(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('-p','--permissions', "Display Permissions") do |val|
      options[:include_feature_access] = true
    end
    opts.on('-f','--feature-access', "Display Permissions [deprecated]") do |val|
      options[:include_feature_access] = true
    end
    opts.add_hidden_option('--feature-access')
    opts.on('-g','--group-access', "Display Group Access") do
      options[:include_group_access] = true
    end
    opts.on('-c','--cloud-access', "Display Cloud Access") do
      options[:include_cloud_access] = true
    end
    opts.on('-i','--instance-type-access', "Display Instance Type Access") do
      options[:include_instance_type_access] = true
    end
    opts.on('-b','--blueprint-access', "Display Blueprint Access") do
      options[:include_blueprint_access] = true
    end
    opts.on('-a','--all-access', "Display All Access Lists") do
      options[:include_feature_access] = true
      options[:include_group_access] = true
      options[:include_cloud_access] = true
      options[:include_instance_type_access] = true
      options[:include_blueprint_access] = true
    end
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a role.\n" +
                  "[name] is required. This is the name or id of a role."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    return 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil

    params.merge!(parse_query_options(options))

    @roles_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @roles_interface.dry.get(, args[0].to_i)
      else
        print_dry_run @roles_interface.dry.list(, {name: args[0]})
      end
      return
    end

    # role = find_role_by_name_or_id(account_id, args[0])
    # exit 1 if role.nil?
    # refetch from show action, argh
    # json_response = @roles_interface.get(account_id, role['id'])
    # role = json_response['role']

    json_response = nil
    if args[0].to_s =~ /\A\d{1,}\Z/
      json_response = @roles_interface.get(, args[0].to_i)
      role = json_response['role']
    else
      role = find_role_by_name_or_id(, args[0])
      exit 1 if role.nil?
      # refetch from show action, argh
      json_response = @roles_interface.get(, role['id'])
      role = json_response['role']
    end

    render_result = render_with_format(json_response, options, 'role')
    return 0 if render_result

    print cyan
    print_h1 "Role Details", options
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'authority',
      "Description" => 'description',
      "Scope" => lambda {|it| it['scope'] },
      "Type" => lambda {|it| format_role_type(it) },
      "Multitenant" => lambda {|it| 
        format_boolean(it['multitenant']).to_s + (it['multitenantLocked'] ? " (LOCKED)" : "")
      },
      "Owner" => lambda {|it| role['owner'] ? role['owner']['name'] : '' },
      #"Account" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
    }
    print_description_list(description_cols, role)

    # print_h2 "Role Instance Limits", options
    # print cyan
    # print_description_list({
    #   "Max Storage"  => lambda {|it| (it && it['maxStorage'].to_i != 0) ? Filesize.from("#{it['maxStorage']} B").pretty : "no limit" },
    #   "Max Memory"  => lambda {|it| (it && it['maxMemory'].to_i != 0) ? Filesize.from("#{it['maxMemory']} B").pretty : "no limit" },
    #   "CPU Count"  => lambda {|it| (it && it['maxCpu'].to_i != 0) ? it['maxCpu'] : "no limit" }
    # }, role['instanceLimits'])

    print_h2 "Permissions", options
    print cyan
    if options[:include_feature_access]
      rows = json_response['featurePermissions'].collect do |it|
        {
          code: it['code'],
          name: it['name'],
          access: format_access_string(it['access']),
        }
      end
      if options[:sort]
        rows.sort! {|a,b| a[options[:sort]] <=> b[options[:sort]] }
      end
      if options[:direction] == 'desc'
        rows.reverse!
      end
      if options[:phrase]
        phrase_regexp = /#{Regexp.escape(options[:phrase])}/i
        rows = rows.select {|row| row[:code].to_s =~ phrase_regexp || row[:name].to_s =~ phrase_regexp }
      end
      print as_pretty_table(rows, [:code, :name, :access], options)
    else
      print cyan,"Use --permissions to list permissions","\n"
    end

    print_h2 "Global Access", options
    puts as_pretty_table([json_response], [
      {"Groups" => lambda {|it| get_access_string(it['globalSiteAccess']) } },
      {"Clouds" => lambda {|it| get_access_string(it['globalZoneAccess']) } },
      {"Instance Types" => lambda {|it| get_access_string(it['globalInstanceTypeAccess']) } },
      {"Blueprints" => lambda {|it| get_access_string(it['globalAppTemplateAccess'] || it['globalBlueprintAccess']) } },
    ], options)

    #print_h2 "Group Access: #{get_access_string(json_response['globalSiteAccess'])}", options
    print cyan
    if json_response['globalSiteAccess'] == 'custom'
      print_h2 "Group Access", options
      if options[:include_group_access]
        rows = json_response['sites'].collect do |it|
          {
            name: it['name'],
            access: format_access_string(it['access'], ["none","read","full"]),
          }
        end
        print as_pretty_table(rows, [:name, :access], options)
      else
        print cyan,"Use -g, --group-access to list custom access","\n"
      end
    else
      # print "\n"
      # print cyan,bold,"Group Access: #{get_access_string(json_response['globalSiteAccess'])}",reset,"\n"
    end
    
    print cyan
    #puts "Cloud Access: #{get_access_string(json_response['globalZoneAccess'])}"
    #print "\n"
    if json_response['globalZoneAccess'] == 'custom'
      print_h2 "Cloud Access", options
      if options[:include_cloud_access]
        rows = json_response['zones'].collect do |it|
          {
            name: it['name'],
            access: format_access_string(it['access'], ["none","read","full"]),
          }
        end
        print as_pretty_table(rows, [:name, :access], options)
      else
        print cyan,"Use -c, --cloud-access to list custom access","\n"
      end
    else
      # print "\n"
      # print cyan,bold,"Cloud Access: #{get_access_string(json_response['globalZoneAccess'])}",reset,"\n"
    end

    print cyan
    # puts "Instance Type Access: #{get_access_string(json_response['globalInstanceTypeAccess'])}"
    # print "\n"
    if json_response['globalInstanceTypeAccess'] == 'custom'
      print_h2 "Instance Type Access", options
      if options[:include_instance_type_access]
        rows = json_response['instanceTypePermissions'].collect do |it|
          {
            name: it['name'],
            access: format_access_string(it['access'], ["none","read","full"]),
          }
        end
        print as_pretty_table(rows, [:name, :access], options)
      else
        print cyan,"Use -i, --instance-type-access to list custom access","\n"
      end
    else
      # print "\n"
      # print cyan,bold,"Instance Type Access: #{get_access_string(json_response['globalInstanceTypeAccess'])}",reset,"\n"
    end

    blueprint_global_access = json_response['globalAppTemplateAccess'] || json_response['globalBlueprintAccess']
    blueprint_permissions = json_response['appTemplatePermissions'] || json_response['blueprintPermissions'] || []
    print cyan
    # print_h2 "Blueprint Access: #{get_access_string(json_response['globalAppTemplateAccess'])}", options
    # print "\n"
    if blueprint_global_access == 'custom'
      print_h2 "Blueprint Access", options
      if options[:include_blueprint_access]
        rows = blueprint_permissions.collect do |it|
          {
            name: it['name'],
            access: format_access_string(it['access'], ["none","read","full"]),
          }
        end
        print as_pretty_table(rows, [:name, :access], options)
      else
        print cyan,"Use -b, --blueprint-access to list custom access","\n"
      end
    else
      # print "\n"
      # print cyan,bold,"Blueprint Access: #{get_access_string(json_response['globalAppTemplateAccess'])}",reset,"\n"
    end

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#handle(args) ⇒ Object



33
34
35
# File 'lib/morpheus/cli/roles.rb', line 33

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/morpheus/cli/roles.rb', line 37

def list(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List roles."
  end
  optparse.parse!(args)

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    
    params = {}
    params.merge!(parse_list_options(options))
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.list(, params), options
      return
    end
    load_whoami()
    json_response = @roles_interface.list(, params)
    if options[:json]
      puts as_json(json_response, options, "roles")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "roles")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['roles'], options)
      return 0
    end
    roles = json_response['roles']
    title = "Morpheus Roles"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if roles.empty?
      print cyan,"No roles found.",reset,"\n"
    else
      print_roles_table(roles, options.merge({is_master_account: @is_master_account}))
      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_permissions(args) ⇒ Object



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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/morpheus/cli/roles.rb', line 322

def list_permissions(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[role]")
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List the permissions for a role.\n" +
                  "[role] is required. This is the name or id of a role."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    return 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil

    # role = find_role_by_name_or_id(account_id, args[0])
    # exit 1 if role.nil?

    @roles_interface.setopts(options)
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @roles_interface.dry.get(, args[0].to_i)
      else
        print_dry_run @roles_interface.dry.list(, {name: args[0]})
      end
      return
    end

    json_response = nil
    if args[0].to_s =~ /\A\d{1,}\Z/
      json_response = @roles_interface.get(, args[0].to_i)
      role = json_response['role']
    else
      role = find_role_by_name_or_id(, args[0])
      exit 1 if role.nil?
      # refetch from show action, argh
      json_response = @roles_interface.get(, role['id'])
      role = json_response['role']
    end

    role_permissions = json_response['featurePermissions']

    if options[:json]
      puts as_json(role_permissions, options)
      return 0
    elsif options[:yaml]
      puts as_yaml(role_permissions, options)
      return 0
    elsif options[:csv]
      puts records_as_csv(role_permissions)
      return 0
    end

    print cyan
    print_h1 "Role Permissions: [#{role['id']}] #{role['authority']}", options

    print cyan
    if role_permissions && role_permissions.size > 0
      rows = role_permissions.collect do |it|
        {
          code: it['code'],
          name: it['name'],
          access: format_access_string(it['access']),
        }
      end
      if options[:sort]
        rows.sort! {|a,b| a[options[:sort]] <=> b[options[:sort]] }
      end
      if options[:direction] == 'desc'
        rows.reverse!
      end
      if options[:phrase]
        phrase_regexp = /#{Regexp.escape(options[:phrase])}/i
        rows = rows.select {|row| row[:code].to_s =~ phrase_regexp || row[:name].to_s =~ phrase_regexp }
      end
      print as_pretty_table(rows, [:code, :name, :access], options)
    else
      puts "No permissions found"
    end

    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(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
# File 'lib/morpheus/cli/roles.rb', line 601

def remove(args)
  usage = "Usage: morpheus roles remove [name]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  name = args[0]
  connect(options)
  begin

     = (options)
     =  ? ['id'] : nil

    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the role #{role['authority']}?")
      exit
    end
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.destroy(, role['id'])
      return
    end
    json_response = @roles_interface.destroy(, role['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} removed"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/morpheus/cli/roles.rb', line 521

def update(args)
  usage = "Usage: morpheus roles update [name] [options]"
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    build_option_type_options(opts, options, update_role_option_types)
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    exit 1
  end
  name = args[0]
  connect(options)
  begin

    load_whoami()

     = (options)
     =  ? ['id'] : nil

    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'role' => passed_options}) unless passed_options.empty?
    else
      # merge -O options into normally parsed options
      params.deep_merge!(passed_options)
      prompt_option_types = update_role_option_types()
      if !@is_master_account
        prompt_option_types = prompt_option_types.reject {|it| ['roleType', 'multitenant','multitenantLocked'].include?(it['fieldName']) }
      end
      if role['roleType'] != 'user'
        prompt_option_types = prompt_option_types.reject {|it| ['multitenant','multitenantLocked'].include?(it['fieldName']) }
      end
      #params = Morpheus::Cli::OptionTypes.prompt(prompt_option_types, options[:options], @api_client, options[:params])

      if params.empty?
        puts optparse
        option_lines = prompt_option_types.collect {|it| "\t-O #{it['fieldName']}=\"value\"" }.join("\n")
        puts "\nAvailable Options:\n#{option_lines}\n\n"
        exit 1
      end

      payload = {"role" => params}
    end
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update(, role['id'], payload)
      return
    end
    json_response = @roles_interface.update(, role['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
      return
    end
    role = json_response['role']
    display_name = role['authority'] rescue ''
    print_green_success "Updated role #{display_name}"

    get_args = [role['id']] + (options[:remote] ? ["-r",options[:remote]] : [])
    if 
      get_args.push "--account-id", ['id'].to_s
    end
    get(get_args)

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

#update_blueprint_access(args) ⇒ Object



1192
1193
1194
1195
1196
1197
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
# File 'lib/morpheus/cli/roles.rb', line 1192

def update_blueprint_access(args)
  options = {}
  blueprint_id = nil
  access_value = nil
  do_all = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '--blueprint ID', String, "Blueprint ID or Name" ) do |val|
      blueprint_id = val
    end
    opts.on( nil, '--all', "Update all blueprints at once." ) do
      do_all = true
    end
    opts.on( '--access VALUE', String, "Access value [full|read|none]" ) do |val|
      access_value = val
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update role access for an blueprint or all blueprints.\n" +
                  "[name] is required. This is the name or id of a role.\n" + 
                  "--blueprint or --all is required. This is the name or id of a blueprint.\n" + 
                  "--access is required. This is the new access value."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    return 1
  end
  name = args[0]
  # support old usage: [name] [blueprint] [access]
  blueprint_id ||= args[1]
  access_value ||= args[2]

  if (!blueprint_id && !do_all) || !access_value
    puts_error optparse
    return 1
  end
  
  access_value = access_value.to_s.downcase

  if !['full', 'none'].include?(access_value)
    puts optparse
    return 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    return 1 if role.nil?

    role_json = @roles_interface.get(, role['id'])
    blueprint_global_access = role_json['globalAppTemplateAccess'] || role_json['globalBlueprintAccess']
    blueprint_permissions = role_json['appTemplatePermissions'] || role_json['blueprintPermissions'] || []
    if blueprint_global_access != 'custom'
      print "\n", red, "Global Blueprint Access is currently: #{blueprint_global_access.to_s.capitalize}"
      print "\n", "You must first set it to Custom via `morpheus roles update-global-blueprint-access \"#{name}\" custom`"
      print "\n\n", reset
      return 1
    end

    # hacky, but support name or code lookup via the list returned in the show payload
    blueprint = nil
    if !do_all
      if blueprint_id.to_s =~ /\A\d{1,}\Z/
        blueprint = blueprint_permissions.find {|b| b['id'] == blueprint_id.to_i }
      else
        blueprint = blueprint_permissions.find {|b| b['name'] == blueprint_id || b['code'] == blueprint_id }
      end
      if blueprint.nil?
        print_red_alert "Blueprint not found: '#{blueprint_id}'"
        return 1
      end
    end

    params = {}
    if do_all
      params['allAppTemplates'] = true
      #params['allBlueprints'] = true
    else
      params['appTemplateId'] = blueprint['id']
      # params['blueprintId'] = blueprint['id']
    end
    params['access'] = access_value
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_blueprint(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_blueprint(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      if do_all
        print_green_success "Role #{role['authority']} access updated for all blueprints"
      else
        print_green_success "Role #{role['authority']} access updated for blueprint #{blueprint['name']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_cloud_access(args) ⇒ Object



885
886
887
888
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
# File 'lib/morpheus/cli/roles.rb', line 885

def update_cloud_access(args)
  options = {}
  cloud_name = nil
  access_value = nil
  do_all = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-c', '--cloud CLOUD', "Cloud name or id" ) do |val|
      puts "val is : #{val}"
      cloud_name = val
    end
    opts.on( nil, '--all', "Update all clouds at once." ) do
      do_all = true
    end
    opts.on( '--access VALUE', String, "Access value [full|read|none]" ) do |val|
      access_value = val
    end
    opts.on( '-g', '--group GROUP', "Group to find cloud in" ) do |val|
      options[:group] = val
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update role access for a cloud or all clouds.\n" +
                  "[name] is required. This is the name or id of a role.\n" + 
                  "--cloud or --all is required. This is the name or id of a cloud.\n" + 
                  "--access is required. This is the new access value."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    return 1
  end
  name = args[0]
  # support old usage: [name] [cloud] [access]
  cloud_name ||= args[1]
  access_value ||= args[2]

  if (!cloud_name && !do_all) || !access_value
    puts optparse
    return 1
  end
  puts "cloud_name is : #{cloud_name}"
  puts "access_value is : #{access_value}"
  access_value = access_value.to_s.downcase

  if !['full', 'none'].include?(access_value)
    puts optparse
    exit 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    role_json = @roles_interface.get(, role['id'])
    if role_json['globalZoneAccess'] != 'custom'
      print "\n", red, "Global Cloud Access is currently: #{role_json['globalZoneAccess'].capitalize}"
      print "\n", "You must first set it to Custom via `morpheus roles update-global-cloud-access \"#{name}\" custom`"
      print "\n\n", reset
      exit 1
    end

    # crap, group_id is needed for this api, maybe just use infrastructure or some other optionSource instead.
    group_id = nil
    cloud_id = nil
    if !do_all
      group_id = nil
      if !options[:group].nil?
        group = find_group_by_name_or_id_for_provisioning(options[:group])
        group_id = group['id']
      else
        group_id = @active_group_id
      end
      if group_id.nil?
        print_red_alert "Group not found or specified!"
        return 1
      end
      cloud_id = find_cloud_id_by_name(group_id, cloud_name)
      return 1 if cloud_id.nil?
    end
    params = {}
    if do_all
      params['allClouds'] = true
    else
      params['cloudId'] = cloud_id
    end
    params['access'] = access_value
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_cloud(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_cloud(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      if do_all
        print_green_success "Role #{role['authority']} access updated for all clouds"
      else
        print_green_success "Role #{role['authority']} access updated for cloud id #{cloud_id}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_feature_access(args) ⇒ Object



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

def update_feature_access(args)
  usage = "Usage: morpheus roles update-feature-access [name] [code] [full|read|user|yes|no|none]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [code] [full|read|user|yes|no|none]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 3
    puts optparse
    exit 1
  end
  name = args[0]
  permission_code = args[1]
  access_value = args[2].to_s.downcase

  # if !['full_decrypted','full', 'read', 'custom', 'none'].include?(access_value)
  #   puts optparse
  #   exit 1
  # end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    params = {permissionCode: permission_code, access: access_value}
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_permission(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_permission(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} permission #{permission_code} set to #{access_value}"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_global_blueprint_access(args) ⇒ Object



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

def update_global_blueprint_access(args)
  usage = "Usage: morpheus roles update-global-blueprint-access [name] [full|custom|none]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [full|custom|none]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 2
    puts optparse
    exit 1
  end
  name = args[0]
  access_value = args[1].to_s.downcase
  if !['full', 'custom', 'none'].include?(access_value)
    puts optparse
    exit 1
  end


  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    params = {permissionCode: 'AppTemplate', access: access_value}
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_permission(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_permission(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} global blueprint access updated"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_global_cloud_access(args) ⇒ Object



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

def update_global_cloud_access(args)
  usage = "Usage: morpheus roles update-global-cloud-access [name] [full|custom|none]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [full|custom|none]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 2
    puts optparse
    exit 1
  end
  name = args[0]
  access_value = args[1].to_s.downcase
  if !['full', 'custom', 'none'].include?(access_value)
    puts optparse
    exit 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    params = {permissionCode: 'ComputeZone', access: access_value}
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_permission(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_permission(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} global cloud access updated"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_global_group_access(args) ⇒ Object



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
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/morpheus/cli/roles.rb', line 692

def update_global_group_access(args)
  usage = "Usage: morpheus roles update-global-group-access [name] [full|read|custom|none]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [full|read|custom|none]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 2
    puts optparse
    exit 1
  end
  name = args[0]
  access_value = args[1].to_s.downcase
  if !['full', 'read', 'custom', 'none'].include?(access_value)
    puts optparse
    exit 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    params = {permissionCode: 'ComputeSite', access: access_value}
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_permission(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_permission(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} global group access updated"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_global_instance_type_access(args) ⇒ Object



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

def update_global_instance_type_access(args)
  usage = "Usage: morpheus roles update-global-instance-type-access [name] [full|custom|none]"
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [full|custom|none]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
  end
  optparse.parse!(args)

  if args.count < 2
    puts optparse
    exit 1
  end
  name = args[0]
  access_value = args[1].to_s.downcase
  if !['full', 'custom', 'none'].include?(access_value)
    puts optparse
    exit 1
  end


  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    exit 1 if role.nil?

    params = {permissionCode: 'InstanceType', access: access_value}
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_permission(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_permission(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Role #{role['authority']} global instance type access updated"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_group_access(args) ⇒ Object



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

def update_group_access(args)
  options = {}
  name = nil
  group_name = nil
  access_value = nil
  do_all = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '-g', '--group GROUP', "Group name or id" ) do |val|
      group_name = val
    end
    opts.on( nil, '--all', "Update all groups at once." ) do
      do_all = true
    end
    opts.on( '--access VALUE', String, "Access value [full|read|none]" ) do |val|
      access_value = val
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update role access for a group or all groups.\n" +
                  "[name] is required. This is the name or id of a role.\n" + 
                  "--group or --all is required. This is the name or id of a group.\n" + 
                  "--access is required. This is the new access value."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  name = args[0]
  # support old usage: [name] [group] [access]
  group_name ||= args[1]
  access_value ||= args[2]

  if (!group_name && !do_all) || !access_value
    puts optparse
    return 1
  end
  
  access_value = access_value.to_s.downcase

  if !['full', 'read', 'none'].include?(access_value)
    puts optparse
    return 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    return 1 if role.nil?

    role_json = @roles_interface.get(, role['id'])
    if role_json['globalSiteAccess'] != 'custom'
      print "\n", red, "Global Group Access is currently: #{role_json['globalSiteAccess'].capitalize}"
      print "\n", "You must first set it to Custom via `morpheus roles update-global-group-access \"#{name}\" custom`"
      print "\n\n", reset
      exit 1
    end

    group = nil
    group_id = nil
    if !do_all
      group = find_group_by_name_or_id_for_provisioning(group_name)
      return 1 if group.nil?
      group_id = group['id']
    end

    params = {}
    if do_all
      params['allGroups'] = true
    else
      params['groupId'] = group_id
    end
    params['access'] = access_value
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_group(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_group(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      if do_all
        print_green_success "Role #{role['authority']} access updated for all groups"
      else
        print_green_success "Role #{role['authority']} access updated for group #{group['name']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_instance_type_access(args) ⇒ Object



1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
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
# File 'lib/morpheus/cli/roles.rb', line 1047

def update_instance_type_access(args)
  options = {}
  instance_type_name = nil
  access_value = nil
  do_all = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on( '--instance-type INSTANCE_TYPE', String, "Instance Type name" ) do |val|
      instance_type_name = val
    end
    opts.on( nil, '--all', "Update all instance types at once." ) do
      do_all = true
    end
    opts.on( '--access VALUE', String, "Access value [full|read|none]" ) do |val|
      access_value = val
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Update role access for an instance type or all instance types.\n" +
                  "[name] is required. This is the name or id of a role.\n" + 
                  "--instance-type or --all is required. This is the name of an instance type.\n" + 
                  "--access is required. This is the new access value."
  end
  optparse.parse!(args)

  if args.count < 1
    puts optparse
    return 1
  end
  name = args[0]
  # support old usage: [name] [instance-type] [access]
  instance_type_name ||= args[1]
  access_value ||= args[2]

  if (!instance_type_name && !do_all) || !access_value
    puts optparse
    return 1
  end
  
  access_value = access_value.to_s.downcase

  if !['full', 'none'].include?(access_value)
    puts optparse
    return 1
  end

  connect(options)
  begin
     = (options)
     =  ? ['id'] : nil
    role = find_role_by_name_or_id(, name)
    return 1 if role.nil?

    role_json = @roles_interface.get(, role['id'])
    if role_json['globalInstanceTypeAccess'] != 'custom'
      print "\n", red, "Global Instance Type Access is currently: #{role_json['globalInstanceTypeAccess'].capitalize}"
      print "\n", "You must first set it to Custom via `morpheus roles update-global-instance-type-access \"#{name}\" custom`"
      print "\n\n", reset
      return 1
    end

    instance_type = nil
    if !do_all
      instance_type = find_instance_type_by_name(instance_type_name)
      return 1 if instance_type.nil?
    end

    params = {}
    if do_all
      params['allInstanceTypes'] = true
    else
      params['instanceTypeId'] = instance_type['id']
    end
    params['access'] = access_value
    @roles_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @roles_interface.dry.update_instance_type(, role['id'], params)
      return
    end
    json_response = @roles_interface.update_instance_type(, role['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      if do_all
        print_green_success "Role #{role['authority']} access updated for all instance types"
      else
        print_green_success "Role #{role['authority']} access updated for instance type #{instance_type['name']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end