Class: Morpheus::Cli::UserGroupsCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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 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

Instance Method Details

#_get(id, options) ⇒ Object



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

def _get(id, options)

  begin
    user_group = find_user_group_by_name_or_id(nil, id)
    if user_group.nil?
      return 1
    end
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.get(nil, user_group['id'])
      return
    end
    json_response = @user_groups_interface.get(nil, user_group['id'])
    user_group = json_response['userGroup']
    users = user_group['users'] || []
    if options[:json]
      puts as_json(json_response, options, "userGroup")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "userGroup")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['userGroup']], options)
      return 0
    end

    print_h1 "User Group Details"
    print cyan
    print_description_list(user_group_column_definitions, user_group, options)

    ## Users
    print_h2 "Users (#{users.size})"
    if users.size == 0
      print cyan,"No users",reset,"\n"
    else
      user_columns = [
        {"ID" => lambda {|user| user['id'] } },
        {"USERNAME" => lambda {|user| user['username'] } },
        {"NAME" => lambda {|user| user['displayName'] } },
      ]
      print as_pretty_table(users, user_columns)
    end

    print reset,"\n"

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

#add(args) ⇒ Object



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

def add(args)
  options = {}
  params = {}
  user_ids = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--sudoUser [on|off]', String, "Sudo Access") do |val|
      params['sudoUser'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--serverGroup VALUE', String, "Server Group") do |val|
      params['name'] = val
    end
    opts.on('--users LIST', Array, "Users to include in this group, comma separated list of IDs or usernames") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        user_ids = []
      else
        user_ids = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create a new user group." + "\n" +
                  "[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got #{args.count}\n#{optparse}"
    return 1
  end
  # support [name] as first argument
  if args[0]
    params['name'] = args[0]
  end
  connect(options)
  begin
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      users = []
      if user_ids
        user_ids.each do |user_id|
          user = find_user_by_username_or_id(nil, user_id)
          return 1 if user.nil?
          users << user
        end
        params['users'] = users.collect {|it| it['id'] }
      end
      # todo: prompt?
      payload = {'userGroup' => params}
    end
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.create(nil, payload)
      return
    end
    json_response = @user_groups_interface.create(nil, payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      user_group = json_response['userGroup']
      print_green_success "Added user group #{user_group['name']}"
      _get(user_group['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_user(args) ⇒ Object



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

def add_user(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [user]")
    build_common_options(opts, options, [:json, :dry_run, :remote, :quiet])
    opts.footer = "Add a user to a user group.\n" +
                  "[name] is required. This is the name or id of a user group.\n" +
                  "[user] is required. This is the username or id of a user. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    user_group = find_user_group_by_name_or_id(nil, args[0])
    if user_group.nil?
      return 1
    end
    

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      user_ids = args[1..-1]
      users = []
      user_ids.each do |user_id|
        user = find_user_by_username_or_id(nil, user_id)
        return 1 if user.nil?
        users << user
      end
      add_user_ids = users.collect {|it| it['id'] }
      current_users = (user_group['users'] || [])
      current_user_ids = current_users.collect {|it| it['id'] }
      new_user_ids = (current_user_ids + add_user_ids).uniq
      user_group_payload = {} # user_group
      user_group_payload['users'] = new_user_ids
      payload = {'userGroup' => user_group_payload}
    end
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.update(nil, user_group["id"], payload)
      return 0
    end
    json_response = @user_groups_interface.update(nil, user_group["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if users.size == 1
          print_green_success  "Added #{users[0]['username']} to user group #{user_group['name']}"
        else
          print_green_success "Added #{users.size} users to user group #{user_group['name']}"
        end
      _get(user_group['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



12
13
14
15
16
17
# File 'lib/morpheus/cli/commands/user_groups_command.rb', line 12

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @user_groups_interface = @api_client.user_groups
  @account_users_interface = @api_client.
  @accounts_interface = @api_client.accounts
end

#get(args) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/morpheus/cli/commands/user_groups_command.rb', line 72

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  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



19
20
21
# File 'lib/morpheus/cli/commands/user_groups_command.rb', line 19

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
# File 'lib/morpheus/cli/commands/user_groups_command.rb', line 23

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search phrase]")
    build_standard_list_options(opts, options)
    opts.footer = "List user groups."
  end
  optparse.parse!(args)
  # verify_args!(args:args, optparse:optparse, count:0)
  options[:phrase] = args.join(" ") if args.count > 0
  connect(options)
  
  params.merge!(parse_list_options(options))
  @user_groups_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @user_groups_interface.dry.list(nil, params)
    return
  end
  json_response = @user_groups_interface.list(nil, params)

  render_response(json_response, options, "userGroups") do
    if options[:json]
      puts as_json(json_response, options, "userGroups")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response["userGroups"], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "userGroups")
      return 0
    end
    user_groups = json_response['userGroups']
    title = "Morpheus User Groups"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if user_groups.empty?
      print cyan,"No user groups found.",reset,"\n"
    else
      print cyan
      print as_pretty_table(user_groups, list_user_group_column_definitions, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#remove(args) ⇒ Object



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

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :auto_confirm])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 127
  end
  connect(options)

  begin
    user_group = find_user_group_by_name_or_id(nil, args[0])
    if user_group.nil?
      return 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete user group '#{user_group['name']}'?", options)
      return false
    end

    # payload = {
    #   'userGroup' => {id: user_group["id"]}
    # }
    # payload['userGroup'].merge!(user_group)
    payload = params
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.destroy(nil, user_group["id"])
      return
    end

    json_response = @user_groups_interface.destroy(nil, user_group["id"])
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Deleted user group #{user_group['name']}"
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove_user(args) ⇒ Object



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

def remove_user(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [user]")
    build_common_options(opts, options, [:json, :dry_run, :remote, :quiet])
    opts.footer = "Remove a user from a user group.\n" +
                  "[name] is required. This is the name or id of a user group.\n" +
                  "[user] is required. This is the username or id of a user. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    user_group = find_user_group_by_name_or_id(nil, args[0])
    if user_group.nil?
      return 1
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      user_ids = args[1..-1]
      users = []
      user_ids.each do |user_id|
        user = find_user_by_username_or_id(nil, user_id)
        return 1 if user.nil?
        users << user
      end
      remove_user_ids = users.collect {|it| it['id'] }
      current_users = (user_group['users'] || [])
      current_user_ids = current_users.collect {|it| it['id'] }
      new_user_ids = (current_user_ids - remove_user_ids).uniq
      user_group_payload = {} # user_group
      user_group_payload['users'] = new_user_ids
      payload = {'userGroup' => user_group_payload}
    end
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.update(nil, user_group["id"], payload)
      return 0
    end
    json_response = @user_groups_interface.update(nil, user_group["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if users.size == 1
          print_green_success  "Added #{users[0]['username']} to user group #{user_group['name']}"
        else
          print_green_success "Added #{users.size} users to user group #{user_group['name']}"
        end
      _get(user_group['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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

def update(args)
  options = {}
  params = {}
  user_ids = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name for this user group") do |val|
      params['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--sudoUser [on|off]', String, "Sudo Access. Default is off.") do |val|
      params['sudoUser'] = val.nil? || val.to_s == 'on' || val.to_s == 'true'
    end
    opts.on('--users LIST', Array, "Users to include in this group, comma separated list of IDs or usernames") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        user_ids = []
      else
        user_ids = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Update a user group." + "\n" +
                  "[name] is required. This is the name or id of a user group."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    user_group = find_user_group_by_name_or_id(nil, args[0])
    if user_group.nil?
      return 1
    end
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      if user_ids
        users = []
        user_ids.each do |user_id|
          user = find_user_by_username_or_id(nil, user_id)
          return 1 if user.nil?
          users << user
        end
        params['users'] = users.collect {|it| it['id'] }
      else
        # prevent server from clearing this!
        params['users'] = user_group['users'] #.collect {|it| it['id'] }
      end
      # todo: prompt?
      payload = {'userGroup' => params}
    end
    @user_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_groups_interface.dry.update(nil, user_group["id"], payload)
      return
    end
    json_response = @user_groups_interface.update(nil, user_group["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Updated user group #{user_group['name']}"
      _get(user_group['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end