Class: Morpheus::Cli::SecurityGroups

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Class Method Summary collapse

Instance Method Summary collapse

Methods included from InfrastructureHelper

#cloud_type_for_id, #cloud_type_for_name, #cloud_type_for_name_or_id, #clouds_interface, #find_cloud_by_id, #find_cloud_by_name, #find_cloud_by_name_or_id, #find_group_by_id, #find_group_by_name, #find_group_by_name_or_id, #find_network_by_id, #find_network_by_name, #find_network_by_name_or_id, #find_network_group_by_id, #find_network_group_by_name, #find_network_group_by_name_or_id, #find_network_server_type_by_id, #find_network_server_type_by_name, #find_network_server_type_by_name_or_code, #find_network_server_type_by_name_or_id, #find_network_type_by_id, #find_network_type_by_name, #find_network_type_by_name_or_id, #find_resource_pool_group_by_id, #find_resource_pool_group_by_name, #find_resource_pool_group_by_name_or_id, #find_subnet_by_id, #find_subnet_by_name, #find_subnet_by_name_or_id, #find_subnet_type_by_id, #find_subnet_type_by_name, #find_subnet_type_by_name_or_id, #format_network_pool_server_status, #get_available_cloud_types, #groups_interface, included, #network_groups_interface, #network_pool_server_column_definitions, #network_pool_server_list_column_definitions, #network_pool_server_type_column_definitions, #network_pool_server_type_list_column_definitions, #network_server_type_column_definitions, #network_server_type_list_column_definitions, #network_types_interface, #networks_interface, #prompt_for_network, #prompt_for_networks, #prompt_for_pools, #prompt_for_subnets, #resource_pool_groups_interface, #resource_pools_interface, #subnet_types_interface, #subnets_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

Class Method Details

.load_security_group_fileObject



1125
1126
1127
1128
1129
1130
1131
1132
# File 'lib/morpheus/cli/commands/security_groups.rb', line 1125

def self.load_security_group_file
  remote_file = security_group_file_path
  if File.exist? remote_file
    return YAML.load_file(remote_file)
  else
    {}
  end
end

.save_security_group(new_config) ⇒ Object



1138
1139
1140
1141
1142
1143
1144
1145
1146
# File 'lib/morpheus/cli/commands/security_groups.rb', line 1138

def self.save_security_group(new_config)
  fn = security_group_file_path
  if !Dir.exist?(File.dirname(fn))
    FileUtils.mkdir_p(File.dirname(fn))
  end
  File.open(fn, 'w') {|f| f.write new_config.to_yaml } #Store
  FileUtils.chmod(0600, fn)
  new_config
end

.security_group_file_pathObject



1134
1135
1136
# File 'lib/morpheus/cli/commands/security_groups.rb', line 1134

def self.security_group_file_path
  File.join(Morpheus::Cli.home_directory,"securitygroup")
end

Instance Method Details

#add(args) ⇒ Object



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
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
393
394
395
396
# File 'lib/morpheus/cli/commands/security_groups.rb', line 209

def add(args)
  params = {}
  options = {:options => {}}
  cloud_id = nil
  resource_pool_id = nil
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on( '--name Name', String, "Name of the security group" ) do |val|
      options[:options]['name'] = val
    end
    opts.on( '--description Description', String, "Description of the security group" ) do |val|
      options[:options]['description'] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Scoped Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.on( '--resource-pool ID', String, "ID of the Resource Pool for Amazon VPC and Azure Resource Group" ) do |val|
      resource_pool_id = val
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--can-manage LIST', Array, "Tenant Can Manage, comma separated list of account IDs that can manage") do |list|
      options['canManage'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a security group") do |val|
      options[:options]['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Create a security group." + "\n" +
                  "[name] is required. This is the name of the security group."
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  if args[0]
    options[:options]['name'] = args[0]
  end
  connect(options)
  begin

    # load cloud
    cloud = nil
    if cloud_id
      cloud = find_cloud_by_name_or_id(cloud_id)
      return 1 if cloud.nil?
      options[:options]['zoneId'] = cloud['id'].to_s
    end

    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'securityGroup' => passed_options})  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'securityGroup' => {
        }
      }
      # allow arbitrary -O options
      payload.deep_merge!({'securityGroup' => passed_options})  unless passed_options.empty?

      # Name
      options[:options]['name'] = options[:name] if options.key?(:name)
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true}], options[:options])
      payload['securityGroup']['name'] = v_prompt['name']

      # Description
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false}], options[:options])
      payload['securityGroup']['description'] = v_prompt['description']

      # Scoped Cloud
      # /api/options/clouds requires groupId...
      
      
      begin
        scoped_clouds = [{"name" => "All", "value" => "all"}]
        clouds_response = @options_interface.options_for_source('cloudsForSecurityGroup',{})
        if clouds_response['data']
          clouds_response['data'].each do |it|
            scoped_clouds << {"name" => it['name'], "value" => it['value']}
          end
        end
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zoneId', 'fieldLabel' => 'Scoped Cloud', 'type' => 'select', 'selectOptions' => scoped_clouds, 'required' => false, 'defaultValue' => (payload['securityGroup']['zoneId'] || 'all')}], options[:options], @api_client)
        #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zoneId', 'fieldLabel' => 'Scoped Cloud', 'type' => 'select', 'optionSource' => 'cloudsForSecurityGroup', 'required' => false}], options[:options], @api_client)
        if !v_prompt['zoneId'].to_s.empty? && v_prompt['zoneId'].to_s != 'all' && v_prompt['zoneId'].to_s != '-1'
          payload['securityGroup']['zoneId'] = v_prompt['zoneId']

          cloud = find_cloud_by_id(payload['securityGroup']['zoneId'])
          
          # parse --resource-pool
          # if resource_pool_id
          #   resource_pool = find_resource_pool_by_name_or_id(cloud['id'], resource_pool_id)
          #   return 1 if resource_pool.nil?
          # end

          # prompt for zone specific settings that go under "securityGroup.customOptions" for some reason
          custom_options_values = prompt_security_group_custom_options(options, cloud, resource_pool_id)
          payload['securityGroup'].deep_merge!(custom_options_values)
        end
      rescue => ex
        # raise ex
        print yellow,"Failed to determine the available scoped clouds.",reset,"\n"
      end

      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants'] || options['canManage']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = ((options['tenants'] || []) + (options['canManage'] || [])).uniq
        payload['tenantPermissions']['canManageAccounts'] = options['canManage'] if options['canManage']
      end

      # Visibility
      if options['visibility'] != nil
        payload['securityGroup']['visibility'] = options['visibility']
      end

      # Active
      if options['active'] != nil
        payload['securityGroup']['active'] = options['active']
      end

    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.create(payload)
      return 0
    end
    json_response = @security_groups_interface.create(payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    print_green_success "Created security group #{json_response['securityGroup']['name']}"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_location(args) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/morpheus/cli/commands/security_groups.rb', line 572

def add_location(args)
  cloud_id = nil
  resource_pool_id = nil
  params = {}
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [options]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    opts.on( '--resource-pool ID', String, "ID of the Resource Pool for Amazon VPC and Azure Resource Group" ) do |val|
      resource_pool_id = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Add security group to a location (cloud)." + "\n" +
                  "[security-group] is required. This is the name or id of the security group."
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:1)
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'securityGroupLocation' => passed_options})  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'securityGroupLocation' => {
        }
      }
      payload.deep_merge!({'securityGroupLocation' => passed_options})  unless passed_options.empty?

      cloud = nil
      if cloud_id
        options[:options]['zoneId'] = cloud_id
      end
      # Cloud prompt
      scoped_clouds = []
      clouds_response = @options_interface.options_for_source('cloudsForSecurityGroup',{securityGroupId: security_group['id']})
      if clouds_response['data']
        clouds_response['data'].each do |it|
          scoped_clouds << {"name" => it['name'], "value" => it['value']}
        end
      end
      if scoped_clouds.empty?
        raise_command_error("Security group has 0 available clouds for adding a location", args, optparse)
      end
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'zoneId', 'fieldLabel' => 'Cloud', 'type' => 'select', 'selectOptions' => scoped_clouds, 'required' => true}], options[:options], @api_client)
      payload['securityGroupLocation']['zoneId'] = v_prompt['zoneId']
      cloud = find_cloud_by_id(payload['securityGroupLocation']['zoneId'])
      return 1 if cloud.nil?

      # parse --resource-pool
      # if resource_pool_id
      #   resource_pool = find_resource_pool_by_name_or_id(cloud['id'], resource_pool_id)
      #   return 1 if resource_pool.nil?
      # end

      # prompt for zone specific settings that go under "securityGroup.customOptions" for some reason
      custom_options_values = prompt_security_group_custom_options(options, cloud, resource_pool_id)
      payload['securityGroupLocation'].deep_merge!(custom_options_values)
    end
    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.create_location(security_group['id'], payload)
      return 0
    end
    json_response = @security_groups_interface.create_location(security_group['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    print_green_success "Created security group location #{security_group['name']} - #{cloud['name']}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add_rule(args) ⇒ Object



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

def add_rule(args)
  params = {}
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [options]")
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.on( '--name VALUE', String, "Name of the rule" ) do |val|
      options[:options]['name'] = val
    end
    opts.on( '--direction VALUE', String, "Direction" ) do |val|
      options[:options]['direction'] = val
    end
    opts.on( '--rule-type VALUE', String, "Rule Type" ) do |val|
      options[:options]['ruleType'] = val
    end
    opts.on( '--protocol VALUE', String, "Protocol" ) do |val|
      options[:options]['protocol'] = val
    end
    opts.on( '--port-range VALUE', String, "Port Range" ) do |val|
      options[:options]['portRange'] = val
    end
    opts.on( '--source-type VALUE', String, "Source Type" ) do |val|
      options[:options]['sourceType'] = val
    end
    opts.on( '--source VALUE', String, "Source" ) do |val|
      options[:options]['source'] = val
    end
    opts.on( '--source-group VALUE', String, "Source Security Group" ) do |val|
      options[:options]['sourceGroup'] = val
    end
    opts.on( '--source-tier VALUE', String, "Source Tier" ) do |val|
      options[:options]['sourceTier'] = val
    end
    opts.on( '--destination-type VALUE', String, "Destination Type" ) do |val|
      options[:options]['destinationType'] = val
    end
    opts.on( '--destination VALUE', String, "Destination" ) do |val|
      options[:options]['destination'] = val
    end
    opts.on( '--destination-group VALUE', String, "Destination Security Group" ) do |val|
      options[:options]['destinationGroup'] = val
    end
    opts.on( '--destination-tier VALUE', String, "Destination Tier" ) do |val|
      options[:options]['destinationTier'] = val
    end
    opts.footer = "Create a security group rule." + "\n" +
                  "[security-group] is required. This is the name or id of the security group." + "\n"
                  "[name] is required. This is the name of the security group rule."
  end
  optparse.parse!(args)
  if args.count < 1 || args.count > 2
    raise_command_error "wrong number of arguments, expected 1-2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    # construct payload
    if args[1]
      options[:options]['name'] = args[1]
    end
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'rule' => passed_options})  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'rule' => {
        }
      }
      payload.deep_merge!({'rule' => passed_options})  unless passed_options.empty?

      # prompt
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true}], options[:options])
      payload['rule']['name'] = v_prompt['name'] unless v_prompt['name'].nil?

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'direction', 'fieldLabel' => 'Direction', 'type' => 'select', 'optionSource' => 'securityGroupDirection', 'required' => true, 'defaultValue' => 'ingress'}], options[:options], @api_client)
      payload['rule']['direction'] = v_prompt['direction'] unless v_prompt['direction'].nil?

      rule_types = [{"name" => "Custom Rule", "value" => "customRule"}]
      instance_types = @options_interface.options_for_source('instanceTypes',{})
      if instance_types['data']
        instance_types['data'].each do |it|
          rule_types << {"name" => it['name'], "value" => it['code'] || it['value']}
        end
      end
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'ruleType', 'fieldLabel' => 'Rule Type', 'type' => 'select', 'selectOptions' => rule_types, 'required' => true, 'defaultValue' => 'customRule'}], options[:options], @api_client)
      payload['rule']['ruleType'] = v_prompt['ruleType'] unless v_prompt['ruleType'].nil?
      
      if payload['rule']['ruleType'] == 'customRule'

        protocols = [{"name" => "TCP", "value" => "tcp"}, {"name" => "UDP", "value" => "udp"}, {"name" => "ICMP", "value" => "icmp"}]
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'protocol', 'fieldLabel' => 'Protocol', 'type' => 'select', 'selectOptions' => protocols, 'required' => true, 'defaultValue' => 'tcp'}], options[:options], @api_client)
        payload['rule']['protocol'] = v_prompt['protocol'] unless v_prompt['protocol'].nil?

        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'portRange', 'fieldLabel' => 'Port Range', 'type' => 'text', 'required' => true}], options[:options])
        payload['rule']['portRange'] = v_prompt['portRange'] unless v_prompt['portRange'].nil?

      end

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'sourceType', 'fieldLabel' => 'Source Type', 'type' => 'select', 'optionSource' => 'securityGroupSourceType', 'required' => true, 'defaultValue' => 'cidr'}], options[:options], @api_client, {'rule.securityGroupId': security_group['id'], 'securityGroupRule.direction': payload['rule']['direction']})
      payload['rule']['sourceType'] = v_prompt['sourceType'] unless v_prompt['sourceType'].nil?

      if payload['rule']['sourceType'] == 'cidr'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'source', 'fieldLabel' => 'Source', 'type' => 'text', 'required' => true, 'description' => 'Source CIDR eg. 0.0.0.0/0'}], options[:options])
        payload['rule']['source'] = v_prompt['source'] unless v_prompt['source'].nil?
      elsif payload['rule']['sourceType'] == 'group'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'sourceGroup', 'fieldLabel' => 'Source Security Group', 'type' => 'select', 'optionSource' => 'securityGroups', 'required' => true}], options[:options], @api_client)
        payload['rule']['sourceGroup'] = {"id" => v_prompt['sourceGroup']} unless v_prompt['sourceGroup'].nil?
      elsif payload['rule']['sourceType'] == 'tier'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'sourceTier', 'fieldLabel' => 'Source Tier', 'type' => 'select', 'optionSource' => 'tiers', 'required' => true}], options[:options], @api_client)
        payload['rule']['sourceTier'] = {"id" => v_prompt['sourceTier']} unless v_prompt['sourceTier'].nil?
      end

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'destinationType', 'fieldLabel' => 'Destination Type', 'type' => 'select', 'optionSource' => 'securityGroupDestinationType', 'required' => true, 'defaultValue' => 'instance'}], options[:options], @api_client, {'rule.securityGroupId': security_group['id'], 'securityGroupRule.direction': payload['rule']['direction']})
      payload['rule']['destinationType'] = v_prompt['destinationType'] unless v_prompt['destinationType'].nil?

      if payload['rule']['destinationType'] == 'cidr'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'destination', 'fieldLabel' => 'Destination', 'type' => 'text', 'required' => true, 'description' => 'Destination CIDR eg. 0.0.0.0/0'}], options[:options])
        payload['rule']['destination'] = v_prompt['destination'] unless v_prompt['destination'].nil?
      elsif payload['rule']['destinationType'] == 'group'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'destinationGroup', 'fieldLabel' => 'Destination Security Group', 'type' => 'select', 'optionSource' => 'securityGroups', 'required' => true}], options[:options], @api_client)
        payload['rule']['destinationGroup'] = {"id" => v_prompt['destinationGroup']} unless v_prompt['destinationGroup'].nil?
      elsif payload['rule']['destinationType'] == 'tier'
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'destinationTier', 'fieldLabel' => 'Destination Tier', 'type' => 'select', 'optionSource' => 'tiers', 'required' => true}], options[:options], @api_client)
        payload['rule']['destinationTier'] = {"id" => v_prompt['destinationTier']} unless v_prompt['destinationTier'].nil?
      end

    end

    @security_group_rules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_group_rules_interface.dry.create(security_group['id'], payload)
      return 0
    end
    json_response = @security_group_rules_interface.create(security_group['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    display_name = (json_response['rule'] && json_response['rule']['name'].to_s != '') ? json_response['rule']['name'] : json_response['rule']['id']
    print_green_success "Created security group rule #{display_name}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/morpheus/cli/commands/security_groups.rb', line 12

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @security_groups_interface = @api_client.security_groups
  @security_group_rules_interface = @api_client.security_group_rules
  @cloud_resource_pools_interface = @api_client.cloud_resource_pools
  @clouds_interface = @api_client.clouds
  @options_interface = @api_client.options
  @active_security_group = ::Morpheus::Cli::SecurityGroups.load_security_group_file
  @network_security_servers = @api_client.network_security_servers
  @network_servers = @api_client.network_servers
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a security group."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  exit_code, err = 0, nil
  
    security_group_id = nil
    if args[0].to_s =~ /\A\d{1,}\Z/
      security_group_id = args[0].to_i
    else
      security_group = find_security_group_by_name(args[0])
      return 1, "Security Group not found" if security_group.nil?
      security_group_id = security_group['id']
    end
    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.get(security_group_id)
      return exit_code, err
    end
    json_response = @security_groups_interface.get(security_group_id)
    render_result = render_with_format(json_response, options, 'securityGroup')
    return exit_code, err if render_result

    security_group = json_response['securityGroup']
    security_group_locations = json_response['locations'] || security_group['locations']
    security_group_rules = json_response['rules'] || security_group['rules']

    print_h1 "Security Group Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      "Name" => 'name',
      "Description" => 'description',
      "Scoped Cloud" => lambda {|it| it['zone'] ? it['zone']['name'] : 'All' },
      "Source" => lambda {|it| it['syncSource'] == 'external' ? 'SYNCED' : 'CREATED' },
      "Visibility" => 'visibility',
      "Active" => lambda {|it| format_boolean(it['active']) },
      "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.sort.join(', ') : '' },
    }
    print_description_list(description_cols, security_group)
    # print reset,"\n"

    if security_group['resourcePermission'].nil?
      #print "\n", "No group access found", "\n"
    else
      print_h2 "Group Access"
      rows = []
      if security_group['resourcePermission']['all']
        rows.push({"name" => 'All'})
      end
      if security_group['resourcePermission']['sites']
        security_group['resourcePermission']['sites'].each do |site|
          rows.push(site)
        end
      end
      rows = rows.collect do |site|
        {group: site['name'], default: site['default'] ? 'Yes' : ''}
      end
      columns = [:group, :default]
      print cyan
      print as_pretty_table(rows, columns)
    end

    if security_group_locations && security_group_locations.size > 0
      print_h2 "Locations"
      print cyan
      location_cols = {
        "ID" => 'id',
        "CLOUD" => lambda {|it| it['zone'] ? it['zone']['name'] : '' },
        "EXTERNAL ID" => lambda {|it| it['externalId'] },
        "RESOURCE POOL" => lambda {|it| it['zonePool'] ? it['zonePool']['name'] : '' }
      }
      puts as_pretty_table(security_group_locations, location_cols)
    else
      print reset,"\n"
    end

    if security_group_rules
      if security_group_rules == 0
        #print cyan,"No rules.",reset,"\n"
      else
        print_h2 "Rules"
        print cyan
        # NAME  DIRECTION SOURCE  DESTINATION RULE TYPE PROTOCOL  PORT RANGE
        rule_cols = {
          "ID" => 'id',
          "NAME" => 'name',
          "DIRECTION" => lambda {|it| it['direction'] },
          "SOURCE" => lambda {|it| 
            if it['sourceType'] == 'cidr'
              "Network: #{it['source']}"
            elsif it['sourceType'] == 'group'
              "Group: #{it['sourceGroup'] ? it['sourceGroup']['name'] : ''}"
            elsif it['sourceType'] == 'tier'
              "Tier: #{it['sourceTier'] ? it['sourceTier']['name'] : ''}"
            elsif it['sourceType'] == 'instance'
              "Instance"
            else
              it['sourceType']
            end
          },
          "DESTINATION" => lambda {|it| 
            if it['destinationType'] == 'cidr'
              "Network: #{it['destination']}"
            elsif it['destinationType'] == 'group'
              "Group: #{it['destinationGroup'] ? it['destinationGroup']['name'] : ''}"
            elsif it['destinationType'] == 'tier'
              "Tier: #{it['destinationTier'] ? it['destinationTier']['name'] : ''}"
            elsif it['destinationType'] == 'instance'
              "Instance"
            else
              it['destinationType']
            end
          },
          "RULE TYPE" => lambda {|it| it['ruleType'] == 'customRule' ? 'Custom' : it['ruleType'] },
          "PROTOCOL" => lambda {|it| it['protocol'] },
          "PORT RANGE" => lambda {|it| it['portRange'] }
        }
        puts as_pretty_table(security_group_rules, rule_cols)
      end
    end

    return exit_code, err
end

#handle(args) ⇒ Object



24
25
26
# File 'lib/morpheus/cli/commands/security_groups.rb', line 24

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
71
72
73
74
# File 'lib/morpheus/cli/commands/security_groups.rb', line 29

def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_standard_list_options(opts, options)
    opts.footer = "List security groups."
  end
  optparse.parse!(args)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  connect(options)
  params.merge!(parse_list_options(options))
  @security_groups_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @security_groups_interface.dry.list(params)
    return
  end
  json_response = @security_groups_interface.list(params)
  render_response(json_response, options, "securityGroups") do
    security_groups = json_response['securityGroups']
    title = "Morpheus Security Groups"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles, options
    if security_groups.empty?
      print cyan,"No security groups found.",reset,"\n"
    else
      columns = {
        "ID" => 'id',
        "NAME" => 'name',
        #"DESCRIPTION" => 'description',
        "DESCRIPTION" => lambda {|it| truncate_string(it['description'], 30) },
        #"USED BY" => lambda {|it| it['associations'] ? it['associations'] : '' },
        "SCOPED CLOUD" => lambda {|it| it['zone'] ? it['zone']['name'] : 'All' },
        "SOURCE" => lambda {|it| it['syncSource'] == 'external' ? 'SYNCED' : 'CREATED' }
      }
      print as_pretty_table(security_groups, columns, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
end

#remove(args) ⇒ Object



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

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a security group." + "\n" +
                  "[security-group] is required. This is the name or id of the security group."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the security group: #{security_group['name']}?")
      return 9, "aborted command"
    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.delete(security_group['id'])
      return
    end
    json_response = @security_groups_interface.delete(security_group['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    #list([])
    print_green_success "Removed security group #{args[0]}"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_location(args) ⇒ Object



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/morpheus/cli/commands/security_groups.rb', line 659

def remove_location(args)
  cloud_id = nil
  resource_pool_id = nil
  params = {}
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [options]")
    opts.on( '-c', '--cloud CLOUD', "Cloud Name or ID" ) do |val|
      cloud_id = val
    end
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Remove security group from a location (cloud)." + "\n" +
                  "[security-group] is required. This is the name or id of the security group."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    
    # load cloud
    if cloud_id.nil?
      puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [cloud]\n#{optparse}"
      return 1
    end
    cloud = find_cloud_by_name_or_id(cloud_id)
    return 1 if cloud.nil?

    security_group_location = nil
    if security_group['locations']
      security_group_location = security_group['locations'].find {|it| it['zone']['id'] == cloud['id'] }
    end
    if security_group_location.nil?
      print_red_alert "Security group location not found for cloud #{cloud['name']}"
      return 1
    end

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the security group location #{security_group['name']} - #{cloud['name']}?")
      return 9, "aborted command"
    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.delete_location(security_group['id'], security_group_location['id'])
      return 0
    end
    json_response = @security_groups_interface.delete_location(security_group['id'], security_group_location['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    print_green_success "Created security group location #{security_group['name']} - #{cloud['name']}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove_rule(args) ⇒ Object



877
878
879
880
881
882
883
884
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
# File 'lib/morpheus/cli/commands/security_groups.rb', line 877

def remove_rule(args)
  params = {}
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [id]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a security group rule." + "\n" +
                  "[security-group] is required. This is the name or id of the security group." + "\n"
                  "[rule] is required. This is the name or id of the security group rule."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?
    
    #security_group_rule = find_security_group_rule_by_id(security_group['id'], args[1])
    #return 1 if security_group_rule.nil?

    security_group_rule = nil
    if security_group['rules']
      matching_rules = []
      if args[1].to_s =~ /\A\d{1,}\Z/
        matching_rules = security_group['rules'].select {|it| it['id'].to_s == args[1].to_s }
      else
        matching_rules = security_group['rules'].select {|it| it['name'] == args[1].to_s }
      end
      if matching_rules.size > 1
        print_red_alert "#{matching_rules.size} security group rules found by name '#{args[1]}'"
        rows = matching_rules.collect do |it|
          {id: it['id'], name: it['name']}
        end
        puts as_pretty_table(rows, [:id, :name], {color:red})
        return 1
      else
        security_group_rule = matching_rules[0]
      end
    end
    if security_group_rule.nil?
      print_red_alert "Security group rule not found for '#{args[1]}'"
      return 1
    end

    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the security group rule: #{security_group_rule['id']}?")
      return 9, "aborted command"
    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_group_rules_interface.dry.delete(security_group['id'], security_group_rule['id'])
      return 0
    end
    json_response = @security_group_rules_interface.delete(security_group['id'], security_group_rule['id'])
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    display_name = (security_group_rule['name'].to_s != '') ? security_group_rule['name'] : security_group_rule['id'].to_s
    print_green_success "Deleted security group rule #{display_name}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#unuse(args) ⇒ Object



1121
1122
1123
# File 'lib/morpheus/cli/commands/security_groups.rb', line 1121

def unuse(args)
  use(args + ['--none'])
end

#update(args) ⇒ Object



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/morpheus/cli/commands/security_groups.rb', line 398

def update(args)
  params = {}
  options = {:options => {}}
  tenants = nil
  group_access_all = nil
  group_access_list = nil
  group_defaults_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [options]")
    opts.on( '--name Name', String, "Name of the security group" ) do |val|
      options[:options]['name'] = val
    end
    opts.on( '--description Description', String, "Description of the security group" ) do |val|
      options[:options]['description'] = val
    end
    opts.on('--group-access-all [on|off]', String, "Toggle Access for all groups.") do |val|
      group_access_all = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--group-access LIST', Array, "Group Access, comma separated list of group IDs.") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_access_list = []
      else
        group_access_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--group-defaults LIST', Array, "Group Default Selection, comma separated list of group IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        group_defaults_list = []
      else
        group_defaults_list = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--tenants LIST', Array, "Tenant Access, comma separated list of account IDs") do |list|
      if list.size == 1 && list[0] == 'null' # hacky way to clear it
        options['tenants'] = []
      else
        options['tenants'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
      end
    end
    opts.on('--can-manage LIST', Array, "Tenant Can Manage, comma separated list of account IDs that can manage") do |list|
      options['canManage'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    end
    opts.on('--visibility [private|public]', String, "Visibility") do |val|
      options['visibility'] = val
    end
    opts.on('--active [on|off]', String, "Can be used to disable a security group") do |val|
      options[:options]['active'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a security group." + "\n" +
                  "[security-group] is required. This is the name or id of the security group."
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    # construct payload
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload['securityGroup'].deep_merge!(passed_options)  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'securityGroup' => {
        }
      }
      # allow arbitrary -O options
      payload['securityGroup'].deep_merge!(passed_options)  unless passed_options.empty?
      
      # Group Access
      if group_access_all != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['all'] = group_access_all
      end
      if group_access_list != nil
        payload['resourcePermissions'] ||= {}
        payload['resourcePermissions']['sites'] = group_access_list.collect do |site_id|
          site = {"id" => site_id.to_i}
          if group_defaults_list && group_defaults_list.include?(site_id)
            site["default"] = true
          end
          site
        end
      end

      # Tenants
      if options['tenants'] || options['canManage']
        payload['tenantPermissions'] = {}
        payload['tenantPermissions']['accounts'] = ((options['tenants'] || []) + (options['canManage'] || [])).uniq
        payload['tenantPermissions']['canManageAccounts'] = options['canManage'] if options['canManage']
      end

      # Visibility
      if options['visibility'] != nil
        payload['securityGroup']['visibility'] = options['visibility']
      end

      # Active
      if options['active'] != nil
        payload['securityGroup']['active'] = options['active']
      end

      if payload['securityGroup'].empty? && payload['tenantPermissions'].nil? && payload['resourcePermissions'].nil?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end

    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_groups_interface.dry.update(security_group['id'], payload)
      return 0
    end
    json_response = @security_groups_interface.update(security_group['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    print_green_success "Updated security group #{json_response['securityGroup']['name']}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_rule(args) ⇒ Object



947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/morpheus/cli/commands/security_groups.rb', line 947

def update_rule(args)
  params = {}
  options = {:options => {}}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[security-group] [rule]")
    opts.on( '--name VALUE', String, "Name of the rule" ) do |val|
      options[:options]['name'] = val
    end
    opts.on( '--direction VALUE', String, "Direction" ) do |val|
      options[:options]['direction'] = val
    end
    opts.on( '--rule-type VALUE', String, "Rule Type" ) do |val|
      options[:options]['ruleType'] = val
    end
    opts.on( '--protocol VALUE', String, "Protocol" ) do |val|
      options[:options]['protocol'] = val
    end
    opts.on( '--port-range VALUE', String, "Port Range" ) do |val|
      options[:options]['portRange'] = val
    end
    opts.on( '--source-type VALUE', String, "Source Type" ) do |val|
      options[:options]['sourceType'] = val
    end
    opts.on( '--source VALUE', String, "Source" ) do |val|
      options[:options]['source'] = val
    end
    opts.on( '--source-group VALUE', String, "Source Security Group" ) do |val|
      options[:options]['sourceGroup'] = val
    end
    opts.on( '--source-tier VALUE', String, "Source Tier" ) do |val|
      options[:options]['sourceTier'] = val
    end
    opts.on( '--destination-type VALUE', String, "Destination Type" ) do |val|
      options[:options]['destinationType'] = val
    end
    opts.on( '--destination VALUE', String, "Destination" ) do |val|
      options[:options]['destination'] = val
    end
    opts.on( '--destination-group VALUE', String, "Destination Security Group" ) do |val|
      options[:options]['destinationGroup'] = val
    end
    opts.on( '--destination-tier VALUE', String, "Destination Tier" ) do |val|
      options[:options]['destinationTier'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
    opts.footer = "Update a security group rule." + "\n" +
                  "[security-group] is required. This is the name or id of the security group." + "\n"
                  "[rule] is required. This is the name or id of the security group rule."
  end
  optparse.parse!(args)
  if args.count != 2
    raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?
    
    #security_group_rule = find_security_group_rule_by_id(security_group['id'], args[1])
    #return 1 if security_group_rule.nil?

    security_group_rule = nil
    if security_group['rules']
      matching_rules = []
      if args[1].to_s =~ /\A\d{1,}\Z/
        matching_rules = security_group['rules'].select {|it| it['id'].to_s == args[1].to_s }
      else
        matching_rules = security_group['rules'].select {|it| it['name'] == args[1].to_s }
      end
      if matching_rules.size > 1
        print_red_alert "#{matching_rules.size} security group rules found by name '#{args[1]}'"
        rows = matching_rules.collect do |it|
          {id: it['id'], name: it['name']}
        end
        puts as_pretty_table(rows, [:id, :name], {color:red})
        return 1
      else
        security_group_rule = matching_rules[0]
      end
    end
    if security_group_rule.nil?
      print_red_alert "Security group rule not found for '#{args[1]}'"
      return 1
    end

    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'rule' => passed_options})  unless passed_options.empty?
    else
      # prompt for resource folder options
      payload = {
        'rule' => {
        }
      }
      payload.deep_merge!({'rule' => passed_options})  unless passed_options.empty?

      if passed_options.empty?
        raise_command_error "Specify at least one option to update.\n#{optparse}"
      end

    end

    @security_groups_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @security_group_rules_interface.dry.update(security_group['id'], security_group_rule['id'], payload)
      return 0
    end
    json_response = @security_group_rules_interface.update(security_group['id'], security_group_rule['id'], payload)
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    security_group_rule = json_response['rule']
    display_name = (security_group_rule['name'].to_s != '') ? security_group_rule['name'] : security_group_rule['id'].to_s
    print_green_success "Updated security group rule #{display_name}"
    get([security_group['id']])
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#use(args) ⇒ Object

JD: still need this??



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

def use(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id] [--none]")
    opts.on('--none','--none', "Do not use an active group.") do |json|
      options[:unuse] = true
    end
    build_common_options(opts, options, [])
  end
  optparse.parse!(args)
  if args.length < 1 && !options[:unuse]
    puts optparse
    return
  end
  connect(options)
  begin

    if options[:unuse]
      if @active_security_group[@appliance_name.to_sym] 
        @active_security_group.delete(@appliance_name.to_sym)
      end
      ::Morpheus::Cli::SecurityGroups.save_security_group(@active_security_group)
      unless options[:quiet]
        print cyan
        puts "Switched to no active security group."
        print reset
      end
      print reset
      return # exit 0
    end

    security_group = find_security_group_by_name_or_id(args[0])
    return 1 if security_group.nil?

    if !security_group.nil?
      @active_security_group[@appliance_name.to_sym] = security_group['id']
      ::Morpheus::Cli::SecurityGroups.save_security_group(@active_security_group)
      puts cyan, "Using Security Group #{args[0]}", reset
    else
      puts red, "Security Group not found", reset
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end